I am trying to understand the topic of networking by writing java-programs (learning by doing). I wrote a client and a server in java using java.net.Socket. The client is a class and the server is a class. Then I instantiated the two classes in one Main-class. The java-Application run on my computer. When I assign the same port to the client and the server, then I get no error (ex: port 80). But when I assign different ports (ex: port 80 to server and port 9090 to client) then I get an error. Should I use the same port for tcp-connection? I want to understand why I get an error. here is my whole code put in one java-package:
package client_server;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
import java.util.Date;
public class Server {
ServerSocket server;
Server(){
System.out.println("server starts");
try{
//server runs on port 9090
server=new ServerSocket(9090);
}catch(IOException e){
e.printStackTrace();
}
}
void listen(){
Socket socket = null;
try {
System.out.println("server is listining");
socket=server.accept();
PrintWriter out =new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package client_server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.*;
public class Client {
Socket clientSocket;
Client(){
System.out.println("Client starts");
final String server_ip_adress="127.0.0.1";
try {
clientSocket = new Socket(server_ip_adress,80);
} catch (IOException e) {
e.printStackTrace();
}
}
void connectToServer(){
try{
System.out.println("client connects to server");
InputStream clientInput=clientSocket.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(clientInput));
String answer = input.readLine();
System.out.println(answer);
}catch(IOException e){
e.printStackTrace();
}
}
}
package client_server;
public class Main {
public static void main(String [] args){
Server server = new Server();
Client client = new Client();
server.listen();
client. connectToServer();
}
}
Theoretically it should work, because each process (server-process and client process) will be assigned a port and it does not matter if the interprocess-communication occurs on different ports.
But in my case I have one process. So when I assign different ports it throw an error. Is my analysis correct? I getthis error: Address already in use: JVM_Bind