为什么这个线程网络代码不起作用? (爪哇)
服务器代码:
http://stikked.com/view/64826511
客户端网络代码:
http://stikked.com/view/38974838
基本上,客户端连接到服务器,但除此之外,这是行不通的。 当发送消息时,客户端的 System.out.println 指示 GUI 正在调用正确的函数。 但没有迹象表明服务器收到过输入。 如果我远程登录到服务器,它会正常工作。
这是我第一次独立尝试线程代码和 java 网络。 到目前为止,我的大部分编程都是网络应用程序或非常简单的桌面应用程序(例如计算器)。
(如果你的答案是“你做的都是错的”,请指出客户端-服务器程序的正确教程,其中客户端和服务器都可以随时发送消息。我见过的所有教程都让客户端执行一些硬编码命令,然后退出)
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.
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).
(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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两个迫在眉睫的问题 - 您使用的是
PrintWriter
,这意味着如果它实际上无法与服务器通信,它不会抛出任何异常。 您也没有调用flush()
,因此它很可能只是缓冲数据。我建议:
OutputStreamWriter
而不是PrintWriter
,并适当处理异常。 这也将消除缓冲。 您可能希望将其包装在BufferedWriter
中,然后在“完成”消息后调用flush()
。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 callingflush()
, so it may well just be buffering the data.I would suggest:
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.