Created
April 16, 2018 08:02
-
-
Save MojamojaK/b69bdd482d559e17f4f3cdd5ba352bb9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ClientCommunication using Thread | |
import java.io.*; | |
import java.net.*; | |
import java.util.LinkedList; | |
public class ClientCommunication implements Runnable{ | |
private InetAddress addr = InetAddress.getByName("localhost"); | |
private Socket socket; | |
private BufferedReader in; | |
private PrintWriter out; | |
private LinkedList<Character> inbox = new LinkedList<>(); | |
private boolean stopped = true; | |
ClientCommunication (String args[]) throws IOException{ | |
if (args.length > 0) addr = InetAddress.getByName(args[0]); | |
try { | |
System.out.println("addr = " + addr); | |
socket = new Socket(addr, 8080); | |
System.out.println("socket = " + socket); | |
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream())); | |
this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); | |
stopped = false; | |
new Thread(this).start(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public void run() { | |
while (!stopped) { | |
try { | |
if (in.ready()) { | |
appendInbox((char)in.read()); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public void close() { | |
try { | |
stopped = true; | |
socket.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private synchronized void appendInbox(char message) { | |
inbox.offer(message); | |
} | |
public int inboxSize() { | |
return inbox.size(); | |
} | |
public char getMessage() { | |
return inbox.poll(); | |
} | |
public synchronized void sendMessage(char message) { | |
out.print(message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment