我已编写服务器和客户端部分,请参阅代码:
//this I run on my firt PC
public class TCPServer {
public static void main(String[] args) throws Exception{
TCPServer server = new TCPServer();
server.run();
}
public void run() throws Exception{
ServerSocket socket = new ServerSocket(6789);
Socket SOCK = socket.accept();
BufferedReader BR = new BufferedReader(new InputStreamReader(SOCK.getInputStream()));
String msg = BR.readLine();
System.out.println(msg);
if(msg != null){
PrintStream PS = new PrintStream(SOCK.getOutputStream());
PS.print("MESSAGE RECEIVED");
}
}
}
//This I run on my notebook
public class TCPClient {
public static void main(String args[]) throws Exception{
TCPClient client = new TCPClient();
client.run();
}
public void run() throws Exception{
Socket clientSocket = new Socket("192.168.88.77",6789);
PrintStream PS = new PrintStream(clientSocket.getOutputStream());
PS.print("Hello from GLADIS VLADLEN");
BufferedReader BR = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String msg = BR.readLine();
System.out.println(msg);
}
}
运行此应用程序后没有任何反应。只有在我停止客户端app消息后才被服务器部分接收。为什么会这样?我试图关闭防火墙,但这对我没有帮助。
答案 0 :(得分:1)
服务器和客户端都使用BufferedReader#readLine()
读取一行。但是PrintStream
正在发送没有行终止符的字符。
尝试拨打println
而不是print
。