这是我服务器的代码:
public class Server {
public static void main(String[] args) {
new Server().go();
}
public void go() {
try {
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(5000);
while(true) {
Socket clientSocket = serverSocket.accept();
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("Connection");
}
} catch(Exception e) {
e.printStackTrace();
}
}
public class ClientHandler implements Runnable {
private BufferedReader br;
private Socket socket;
private InputStream is;
public ClientHandler(Socket clientSocket) {
try {
socket = clientSocket;
is = socket.getInputStream();
} catch(Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
int k;
while ((k = is.read()) != -1)
System.out.print((char) k);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
那就是客户:
public class Client {
public static void main(String[] args) {
new Client().connect();
}
public void connect() {
try {
Thread.sleep(100);
Socket socket = new Socket("localhost", 5000);
OutputStream out = socket.getOutputStream();
out.write("Hello World!".getBytes());
out.flush();
System.out.println("Written");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端我连接到localhost,一切正常。但是一旦我通过我的IP / DynDNS地址替换“localhost”,服务器就打印出“连接”,但是没有收到消息。但是,当我添加socket.close()时,会发送消息。如果我使用IP而不是“localhost”,为什么我必须添加socket.close()来发送消息? 我认为这也是我的Android设备无法连接到我的服务器的原因。服务器打印出“连接”,但是我无法写消息(就在我之后立即关闭套接字或者我调用socket.shutDownOutput()时。 我在我的路由器和防火墙上激活了端口转发,但现在我的想法已经用完了......为什么我有连接,但是无法写入?
编辑:我不必完全关闭Socket,我必须关闭PrintWriter。但为什么!?