我创建了一个java聊天应用程序(客户端和服务器) 当我在我的LAN上时(使用服务器的LAN IP地址进入我的客户端),一切正常。
但是当我在我的客户端使用服务器的Internet地址时,只有在我关闭客户端的输出数据流时才会发送字符串(并且所有字符串都会立即发送)。
这是我的代码的快速捕捉(我在下面的示例中将端口从6791转发到6790),
我的服务器(线程):
// this line is actually on my global server class, used below with theServer
ServerSocket svrSocket= new ServerSocket(6790);
//wait for incoming connection
connectionSocket = svrSocket.accept();
connectionSocket.setSoTimeout(10000);
// free the accepting port
svrSocket.close();
//create a new thread to accept future connections (creates a new svrSocket)
theServer.openNewConnection();
//create input stream
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
boolean threadRunning = true);
while (threadRunning) {
//System.out.println("thread: in the while");
try {
Thread.sleep(100);
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
}
catch...
}
我的客户:
InetAddress dnsName;
Socket clientSocket;
PrintWriter out;
dnsName = InetAddress.getByName("myAddress.me");
clientSocket = new Socket(dnsName.getHostAddress(), 6791);
Thread.sleep(10);
out = new PrintWriter(clientSocket.getOutputStream(), true );
int i=140;
while (i>130){
try {
out.println(Integer.toString(i));
out.flush();
Thread.sleep(200);
}
catch(Exception e) {
e.printStackTrace();
}
i--;
}
out.flush();
out.close();
clientSocket.close();
我尝试过DataOutStreams,没什么可做的。
我的服务器只会在客户端调用out.close()
时收到字符串。
是否有理由通过互联网将数据流 关闭以便发送数据?有没有解决的办法?我做错了吗?