问题:客户端没有收到任何消息。
以下是客户端和服务器的完整代码:
客户
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);
}
}
服务器
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");
}
您必须在邮件末尾包含换行符,如果连接未立即更改,则还要刷新PrintWriter,强制自动刷新:
writer.write("Hello user 1\n");
writer.flush();
编辑:
可以使用构造函数new PrintWriter(someOutputStream, true)
在PrintWriter上启用自动刷新
但是,如文档中所述:
如果启用了自动刷新,则只有在调用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){}
}