package com.encrox.twitchbot.client; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import com.encrox.twitchbot.client.messages.Message; public class Client implements Runnable { private volatile Socket socket, iSocket; private volatile BufferedInputStream bis = null; private volatile DataOutputStream dos = null; private volatile DataOutputStream iDos = null; public int connect() { try { socket = new Socket("encrox.com", 5424); bis = new BufferedInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); } catch (UnknownHostException e) { e.printStackTrace(); return MessageTypes.ERROR; } catch (IOException e) { e.printStackTrace(); return MessageTypes.ERROR; } Runtime.getRuntime().addShutdownHook(new Thread(this)); return MessageTypes.OK; } public void login() { try { iSocket = new Socket("encrox.com", 5425); iDos = new DataOutputStream(iSocket.getOutputStream()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void post(String message) { try { iDos.writeInt(message.length()); iDos.write(message.getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } } public void write(byte[] data) { try { dos.write(data); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public int send(Message message) { try { dos.write(message.getID()); dos.write(message.getData()); byte[] res = new byte[4]; bis.read(res); System.out.println(Utils.ba_to_int(res)); return Utils.ba_to_int(res); } catch (IOException e) { e.printStackTrace(); return MessageTypes.ERROR; } } public IRCMessage getMessage() { byte[] user = new byte[32]; byte level; byte[] message; byte[] buffer; try { bis.read(user); buffer = new byte[1]; bis.read(buffer); level = buffer[0]; buffer = new byte[4]; bis.read(buffer); message = new byte [Utils.ba_to_int(buffer)]; bis.read(message); return new IRCMessage(new String(Utils.crop(user), "UTF-8"), level, new String(message, "UTF-8")); } catch (IOException e) { e.printStackTrace(); return null; } } @Override public void run() { try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { dos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { iDos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { iSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }