简体   繁体   English

为什么此线程网络代码不起作用? (JAVA)

[英]Why doesn't this threaded network code work? (Java)

Code for server: 服务器代码:

http://stikked.com/view/64826511 http://stikked.com/view/64826511

Network Code for client: 客户端的网络代码:

http://stikked.com/view/38974838 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. 发送消息时,客户端的System.out.println指示GUI正在调用正确的函数。 But there is no sign of the server ever recieving the in put. 但是没有迹象表明服务器曾经收到过输入。 If I telnet into the server, it functions correctly. 如果我通过telnet连接到服务器,则它可以正常运行。

This is my first unaided attempt at both threaded code, and java networking. 这是我在线程代码和Java网络方面的首次尝试。 Up till now, most of my programming has been web apps or very simple desktop apps (eg 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) (如果您的回答是“您做错了所有事情”,请指向客户端服务器程序的正确教程,客户端和服务器都可以随时发送消息。我所见过的所有教程都让客户端执行了几个硬编码的命令,然后退出)

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. 紧迫的两个问题-您正在使用PrintWriter ,这意味着如果它实际上无法与服务器通信,它将不会引发任何异常。 You're also not calling flush() , so it may well just be buffering the data. 您也不在调用flush() ,因此它很可能只是在缓冲数据。

I would suggest: 我会建议:

  • Use OutputStreamWriter instead of PrintWriter , and handle exceptions appropriately. 使用OutputStreamWriter而不是PrintWriter ,并适当处理异常。 This will remove buffering as well. 这也将删除缓冲。 You may want to wrap it in a BufferedWriter and then call flush() after you're "done" with a message. 可能希望将其包装在BufferedWriter ,然后在完成“处理”消息后调用flush()
  • Specify the appropriate charset, eg UTF-8. 指定适当的字符集,例如UTF-8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM