So, I have two threads - server thread and client thread. I can make the server write, but it is never read by the client. Here is the client, server, and thread created by the server to handle the client connection.
Client - connect to the socket and try ping pong with the server. The client expects the server to talk to him first!
public class ClientMain {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 14285);
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
} catch(IOException e) {
Log.write("Error in client thread ");
Log.write(e);
}
while(true) {
System.out.println("About to read!! :-D");
String fromServer = in.readLine();
System.out.println("From server: " + fromServer);
out.println("PONG");
}
}
}
Server is a method of starting a server. It creates a stream for viewing serverSocket and, if necessary, creates non-resident client streams. Yes, I understand that it is bad practice to define a class inside such a method ... and my apologies if it is difficult to read.
public void start() {
this.running = true;
class Start implements Runnable {
Server server;
Start(Server server) { this.server = server; }
public void run() {
while(server.running) {
try {
Socket socket = server.serverSocket.accept();
Log.write("Accepted socket");
new ClientThread(server,socket).start();
} catch (IOException e) { e.printStackTrace(); }
}
}
}
Thread start = new Thread(new Start(this));
start.start();
}
- . , , .
public void run() {
Log.write("Running clientthread");
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
} catch(IOException e) {
running = false;
Log.write("Error in client thread " + getName());
Log.write(e);
}
while(running) {
try {
String message = messageQueue.poll();
while(message != null) {
out.println(message);
Log.write("wrote message: " + message);
message = messageQueue.poll();
}
String input = in.readLine();
System.out.println("From client: " + input);
server.handle(username,input,this);
}
catch(IOException e) {
Log.write("Error in client thread " + getName() + " username=" + username);
Log.write(e);
break;
}
}
}
:
Accepted socket
Running clientthread
wrote message: PING
, . ( , PING messageQueue, , , , . , ?) , in.readLine()
, , . , , ?
!
!!