I have a class implementing serversocket class and there is another class implementing the client 1. Socket class.
So what I am trying to do is that. After getting the streams I want client to send a number to server and server will in turn respond to client whether it's prime or not. Which is display in an awt.Label.
But I am not able to receive any response.
Here is the code for client's constructor:
public ClientIsPrime() { setLayout(new GridLayout(2,2)); add(new Label("Enter a number: ")); add(numEntry=new TextField(10)); add(checkPrime=new Button("Check if number is Prime")); add(result=new Label("Result is shown here")); try { Socket client = new Socket(InetAddress.getLocalHost(), 5959); in=client.getInputStream(); out=client.getOutputStream(); }catch(UnknownHostException e) { result.setText("Local Host cannot be resolved"); }catch(IOException e) { result.setText("IOException occured"); } checkPrime.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { int num; num=Integer.parseInt(numEntry.getText()); out.write(num); out.flush(); int c; result.setText(""); String s=""; while((c=in.read())!=-1) s+=((char)c); result.setText(s); }catch(IOException e) { result.setText("IOException occured"); }catch(NumberFormatException e) { result.setText("Please enter a valid number."); } } }); } Code for Server:
public static void main(String args[])throws IOException { server=new ServerSocket(5959); socket=server.accept(); System.out.println("connected"); InputStream in=socket.getInputStream(); OutputStream out=socket.getOutputStream(); int c; String numStr=""; while((c=in.read())!=-1) numStr+=((char)c); int num=Integer.parseInt(numStr); if(num==3) out.write("Number is Prime".getBytes()); else out.write("Number is not Prime".getBytes()); out.flush(); in.close(); out.close(); } It isn't a real app. I am learning.