如何连接以下链接中显示的2个java类客户端服务器:
https://systembash.com/a-simple-java-tcp-server-and-tcp-client/
它说我需要使用TCPserver进行编译,我已经尝试在我的IDE中找到编译选项,即Netbeans,但我似乎无法在任何地方找到它。我可以请一些关于如何连接这两个文件的提示,以便服务器文件响应客户端应用程序吗?
答案 0 :(得分:0)
首先,您需要启动服务器(Serversocket),它将等待客户端套接字连接。
ServerSocket serverSocket = new ServerSocket(PORT);
Socket socket = serverSocket.accept();
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
try {
Object object = objectInputStream.readObject();
System.out.println("read by the server\t" + object);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject("this is message by the server");
}catch(Excetion e) {
e.printStackTrace();
}
serversocket接受,而OIS的readObject()方法将阻塞该线程,因此你必须启动一个新线程。
创建套接字对象时,客户端将连接。之后,您可以通过流发送和接收双方的消息。
// host is the localhost IP
Socket socket = new Socket(host, PORT);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject("this is the message by the client");
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
try {
System.out.println("read by the client\t" + objectInputStream.readObject());
}catch(Excetion e) {
e.printStackTrace();
}