Reputation: 79
I am newbie to java network programming so kindly keep that in mind.
I am try to develop a multi threaded java server client application. For Starters I aim to develop a communication channel between a single client and server only. Without threading the communication between a single client-server works fine. Bu when I apply threading the program fails. The messages are not being sent.
MyServer.java
class MyServer {
public static void main(String[] args) {
try {
ServerSocket svc = new ServerSocket(4567);
System.out.println("Server Waiting at Port 4567");
do {
Socket sock = svc.accept();
MyServerThread thread = new MyServerThread(sock);
}while(true);
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
MyServerThread.java
class MyServerThread extends Thread{
Socket sock;
public MyServerThread(Socket sock) {
this.sock = sock;
}
public void run() {
try {
PrintWriter pw = new PrintWriter(sock.getOutputStream());
Scanner cd = new Scanner(sock.getInputStream());
Scanner kb = new Scanner(System.in);
do {
String clientstr = cd.nextLine();
System.out.println("Client: "+clientstr);
if(clientstr.equalsIgnoreCase("quit")) {
break;
}
String str = kb.nextLine();
pw.println(str);
pw.flush();
}while(true);
sock.close();
pw.close();
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
MyClient
class MyClient3 {
public static void main(String[] args) {
try {
InetAddress object = InetAddress.getByName("192.168.18.125");
Socket sock = new Socket(object, 4567);
PrintWriter pw = new PrintWriter(sock.getOutputStream());
Scanner cd = new Scanner(sock.getInputStream());
Scanner kb = new Scanner(System.in);
do {
String str = kb.nextLine();
pw.println(str);
pw.flush();
String strserver = cd.nextLine();
System.out.println("Server: "+strserver);
if(strserver.equalsIgnoreCase("quit")) {
break;
}
}while(true);
sock.close();
pw.close();
}
catch(UnknownHostException ex) {
System.out.println("Unknown Host");
}
catch(IOException ex) {
System.out.println("IO Exception");
}
}
}
Upvotes: 1
Views: 57
Reputation: 712
Your most immediate problem is that you don't call Thread#start() on the Thread after the creation of MyServerThread. However, usually you shouldn't create classes that extend thread. You should create a Runnable instead, and pass that to Thread#new(Runnable).
Upvotes: 1