问题: 客户端不会收到任何消息。
以下是客户端和服务器的完整代码:
客户端
public class Client extends Socket{
public Client(String hostName, int port) throws UnknownHostException, IOException {
super(hostName,port);
BufferedReader in = new BufferedReader(new InputStreamReader(getInputStream()));
while(true) {
String line = in.readLine();
System.out.println("Text received: " + line);
}
}
SERVER
public final class Server extends ServerSocket{
public Server(int port) throws IOException {
super(port);
System.out.println("Server waiting for client 1");
Socket client1 = accept();
PrintWriter writer = new PrintWriter(client1.getOutputStream(), true);
writer.write("Hello user 1");
System.out.println("Server waiting for client 2");
Socket client2 = accept();
PrintWriter writer2 = new PrintWriter(client2.getOutputStream(), true);
writer2.write("Hello user 2");
System.out.println("Clients connected");
}
答案 0 :(得分:6)
您必须在邮件末尾添加换行符,如果连接未立即更改,则刷新PrintWriter,强制自动刷新:
writer.write("Hello user 1\n");
writer.flush();
修改强>
可以使用构造函数new PrintWriter(someOutputStream, true)
但是,如文档中所述:
如果启用了自动刷新,则只有在调用println,printf或format方法之一时才会执行,而不是每当输出换行符时
这意味着即使使用自动刷新,仍然必须在调用write
后手动刷新PrintWriter,并且仍然必须在结尾处包含换行符(\n
)字符串。
编辑2:
以下是功能齐全的客户端/服务器应用程序的一个小示例:
<强>客户端:强>
public static void main(String[] args){
try{
Socket socket = new Socket(HOST_ADDRESS, PORT);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(bufferedReader.readLine());
bufferedReader.close();
socket.close();
}catch(IOException e){}
}
服务器强>
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(PORT);
Socket socket = serverSocket.accept();
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.write("Hello user!\n");
printWriter.flush();
printWriter.close();
socket.close();
serverSocket.close();
}catch(IOException e){}
}