I've been trying to write a simple server-client application in java in which the client sends the number 1 to the server, and the server sends back the following number until the number reaches 21.
For example,
Client sends 1
Server sends 2
Client sends 3
..... 21
However, the program seems to stop after the client sends the number 1.
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
static Socket link = null;
public static void main(String[] args){
int num = 0;
ServerSocket servSock = null;
try {
servSock= new ServerSocket(1234);
} catch (IOException e) {
System.out.println("Cannot bind to port ");
System.exit(1);
}
try {
link = servSock.accept();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("established connections");
Scanner input = null;
try {
input = new Scanner(link.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter output = null;
try {
output = new PrintWriter(link.getOutputStream(),true);
} catch (IOException e) {
e.printStackTrace();
}
while(input.nextInt()!=-1){
num=input.nextInt();
System.out.println("Server recieved " +num+ " from the client");
output.print(num++);
System.out.println("Server sent " +(num++)+ "to the client");
};
System.out.println("\n* Closing connection... *");
try {
link.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
static Socket link=null;
public static void main(String[] args){
int num=0;
try {
link =new Socket(InetAddress.getLocalHost(),1234);
} catch (UnknownHostException e) {
System.out.println("unknown host");
e.printStackTrace();
} catch (IOException e) {
System.out.println("unable to connect");
e.printStackTrace();
}
Scanner input = null;
try {
input = new Scanner(link.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter output = null;
try {
output = new PrintWriter(link.getOutputStream(),true);
} catch (IOException e) {
e.printStackTrace();
}
while (num!=21){
output.print(num++);
System.out.println("client sent " +(num++)+ "to the Server");
num=input.nextInt();
System.out.println("client recieved " +num+ " from the client");
}
output.print(-1);
try {
link.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(" client connection closed");
}
}
I wish someone would be able to tell me what is the problem.
Thanks in advance.


Sign In
Create Account

Back to top









