Im new to threads, and would like to get experience so I am trying to
build a chat server. The idea is to have one thread read from the client socket,
while another thread writes to the client socket. (like AIM) I cannot get them to execeute
concurrently; Need help, any tips, codeeee ?
import java.io.*;
import java.util.*;
import java.net.*;
public class ChatServer implements Runnable{
private static ServerSocket server;
private static Socket client;
private boolean isReader;
public ChatServer(boolean reader) throws Exception{
isReader = reader;
if(server == null)
server = new ServerSocket(1234);
}
public static void main(String[] args){
try{
Runnable r = new ChatServer(true);
Runnable w = new ChatServer(false);
Thread t = new Thread(r);
Thread o = new Thread(w);
t.start();
o.start();
}catch(Exception er){
System.out.println(er);
}
}//main
public void run() {
try{
System.out.println(this);
if(client == null){
client = server.accept();
System.out.println("Connected");
}
if(this.isReader == true){
System.out.println("read ex");
this.read();
}else{
System.out.println("write ex");
this.write();
}
}catch(Exception error){
System.out.println(error);
}
}//run
public void read() throws Exception{
System.out.println("Reading\n");
DataInputStream read = new DataInputStream(client.getInputStream());
int n ;
while((n = read.read()) != -1)
System.out.print((char)n);
}
public void write() throws Exception{
System.out.println("Writing\n");
DataOutputStream write = new DataOutputStream(client.getOutputStream());
write.writeBytes("Chat Server\n");
write.flush();
Scanner sc = new Scanner(System.in);
while(true){
String line = sc.nextLine();
write.writeBytes(line + "\n");
write.flush();
}
}
}//class