Code for server:
服务器代码:
http://stikked.com/view/64826511
Network Code for client:
客户网络代码:
http://stikked.com/view/38974838
Basically, the client connects to the server, but beyond that, it does not work. When a message is sent, the client's System.out.println indicates that the GUI is calling the correct function. But there is no sign of the server ever recieving the in put. If I telnet into the server, it functions correctly.
基本上,客户端连接到服务器,但除此之外,它不起作用。发送消息时,客户端的System.out.println指示GUI正在调用正确的函数。但没有迹象表明服务器曾接受过输入。如果我telnet到服务器,它可以正常运行。
This is my first unaided attempt at both threaded code, and java networking. Up till now, most of my programming has been web apps or very simple desktop apps (e.g. Calculator).
这是我对线程代码和java网络的第一次独立尝试。到目前为止,我的大多数编程都是网络应用程序或非常简单的桌面应用程序(例如计算器)。
(If your answer is "Your doing it all wrong", please point to a correct tutorial for a client-server program where both the client and server can send messages at any time. All the tutorials I've seen have the client execute a few hardcoded commands, then quit)
(如果你的答案是“你做错了”,请指向一个客户端服务器程序的正确教程,客户端和服务器都可以随时发送消息。我见过的所有教程都让客户端执行一个几个硬编码命令,然后退出)
1 个解决方案
#1
3
Two immediate problems - you're using a PrintWriter
, which means it won't throw any exceptions if it can't actually talk to the server. You're also not calling flush()
, so it may well just be buffering the data.
两个直接问题 - 您正在使用PrintWriter,这意味着如果它实际上无法与服务器通信,它将不会抛出任何异常。你也没有调用flush(),所以它可能只是缓冲数据。
I would suggest:
我会建议:
- Use
OutputStreamWriter
instead ofPrintWriter
, and handle exceptions appropriately. This will remove buffering as well. You may want to wrap it in aBufferedWriter
and then callflush()
after you're "done" with a message. - Specify the appropriate charset, e.g. UTF-8.
使用OutputStreamWriter而不是PrintWriter,并适当地处理异常。这也将消除缓冲。您可能希望将其包装在BufferedWriter中,然后在“完成”消息后调用flush()。
指定适当的字符集,例如UTF-8。
#1
3
Two immediate problems - you're using a PrintWriter
, which means it won't throw any exceptions if it can't actually talk to the server. You're also not calling flush()
, so it may well just be buffering the data.
两个直接问题 - 您正在使用PrintWriter,这意味着如果它实际上无法与服务器通信,它将不会抛出任何异常。你也没有调用flush(),所以它可能只是缓冲数据。
I would suggest:
我会建议:
- Use
OutputStreamWriter
instead ofPrintWriter
, and handle exceptions appropriately. This will remove buffering as well. You may want to wrap it in aBufferedWriter
and then callflush()
after you're "done" with a message. - Specify the appropriate charset, e.g. UTF-8.
使用OutputStreamWriter而不是PrintWriter,并适当地处理异常。这也将消除缓冲。您可能希望将其包装在BufferedWriter中,然后在“完成”消息后调用flush()。
指定适当的字符集,例如UTF-8。