我用 Java 编写了一个小型客户端服务器程序。服务器在某个端口上创建一个ServerSocket
并继续监听它。Client
向该服务器发送一些示例信息。当我Client
第一次运行时,服务器接受连接并由服务器打印信息。然后Client
程序退出。当我Client
再次运行时,连接被接受,但是没有打印数据。请检查以下代码。
服务器程序
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(dis.available() > 0) {
System.out.println(dis.readByte());
}
}
}
}
客户计划
package javadaemon;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
} catch(IOException e) {
}
}
}
请帮助我找出为什么下次服务器没有收到数据。