java定时器和socket问题
我正在尝试制作一个程序,通过使用套接字编程和计时器来侦听客户端输入流
,但每当计时器执行时.. 它被挂了
请帮帮我,
这是代码...
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
try
{
ServerUserName=jTextField1.getText();
ss=new ServerSocket(5000);
jButton1.enable(false);
jTextArea1.enable(true);
jTextField2.enable(true);
Timer t=new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
s=ss.accept();
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
jTextArea1.append(dis.readUTF());
}
catch(IOException IOE)
{
}
catch(Exception ex)
{
setLbl(ex.getMessage());
}
}
});
t.start();
}
catch(IOException IOE)
{
}
}
提前致谢
I'm trying to make a program which listens to the client input stream by using socket programming and timer
but whenever timer executes..
it gets hanged
Please help me out
here is the code...
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
try
{
ServerUserName=jTextField1.getText();
ss=new ServerSocket(5000);
jButton1.enable(false);
jTextArea1.enable(true);
jTextField2.enable(true);
Timer t=new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
s=ss.accept();
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
jTextArea1.append(dis.readUTF());
}
catch(IOException IOE)
{
}
catch(Exception ex)
{
setLbl(ex.getMessage());
}
}
});
t.start();
}
catch(IOException IOE)
{
}
}
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使程序多线程化;一个线程监听套接字,另一个线程处理 GUI。使用 SwingUtilities.invokeLater 让 GUI 线程(“事件调度线程”)在网络线程接收数据时执行 GUI 更新。
Make the program multi-threaded; one thread listens on the socket, the other one handles the GUI. Use SwingUtilities.invokeLater to let the GUI thread ("event dispatching thread") do the GUI updates whenever the network thread receives data.
每次调用
accept
都会等待新客户端连接到服务器。该调用将阻塞,直到建立连接。听起来您有一个客户端维护与服务器的连接。一种解决方案是将
代码的计时器部分拉出外部。
更新:请注意,如果没有数据可供读取,
readUTF
仍然会阻塞。Every call to
accept
waits for a new client to connect to the server. The call blocks until a connection is established. It sounds like you have a single client that maintains a connection to the server.One solution is to pull
outside of the timer portion of the code.
Update: Be aware though that
readUTF
is still going to block if there is no data available to be read.我认为你想使用套接字超时而不是计时器:
I think you want to use socket timeouts instead of a timer: