我想做的是:
1)创建一个TCP套接字,侦听本地计算机中的特定端口号。 (服务器)
2)创建另一个TCP套接字,它将连接到我创建的第一个TCP套接字。(客户端)
3)通过客户端向服务器发送一些数据。
4)客户从服务器接收数据。
5)不要关闭连接..等一会儿..
6)从服务器接收更多数据。
这是我的代码:
public class MyTCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
outToClient.writeBytes(String.valueOf(System.currentTimeMillis()));
Thread.sleep(1000);
outToClient.writeBytes(String.valueOf(System.currentTimeMillis()));
}
}
}
因此,此TCP套接字侦听端口6789.请注意,它从客户端发送回收到的字符串,对其进行大写并将其返回。然后服务器发送currentTimeMillis,等待1000毫秒,然后再次发送timeMillis。
这是我的客户:
public class MyTCPClient {
public static void main(String[] args) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
}
然而,当我测试我的代码时,我得到了:
Received: asdf
Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
at java.io.DataOutputStream.writeBytes(DataOutputStream.java:259)
at MyTCPServer.main(MyTCPServer.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
如何在客户端保持连接活动?此外,我希望能够从客户端发送更多文本。
答案 0 :(得分:4)
最简单的方法是在客户端代码中放置一个循环。像这样:
while ((modifiedSentence = inFromServer.readLine()) != null) {
System.out.println("FROM SERVER: " + modifiedSentence);
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
}
readLine()
方法在等待来自服务器的消息时阻塞,因此客户端不会退出。
请参阅下面有关如何编写套接字服务器和客户端的简单教程:
http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
答案 1 :(得分:0)
您的客户退出。它不会尝试“保持连接活动”。您的服务器将数据写入客户端未读取的客户端。所以它得到它应该得到的异常。如果您想避免异常,请添加缺少的读数。