我有以下TCP客户端代码:
public static void register(InetAddress ip, int port, String name) {
try {
Socket clientSocket = new Socket(ip, port);
send("reg:" + name);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void send(String str) {
try {
String sentence = str;
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(sentence);
} catch (IOException e) {
Log.e("CONNECT", e.getMessage());
}
}
他们都在onClicks中调用,我肯定知道。 我还有以下服务器代码:
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9876);
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);
outToClient.writeBytes("msg: Hello! kalin pedro");
}
}
当尝试向服务器发送数据时,我没有得到异常,我也知道我已经连接到它,因为当我终止服务器应用程序时应用程序崩溃了。问题是服务器在我终止客户端应用程序之前没有收到任何内容。我在那个时刻尝试发送的所有内容都是立即从服务器收到的。我查看了Android Studio提供的网络活动标签,发送数据时发生了变化,服务器刚刚收到它(或者至少我没看到它收到它),直到我终止客户端应用