帮忙看一看,到底什么问题??

osheatangjie 2007-09-19 05:37:49
想写一个一人对一人的聊天程序可是遇到了些问题;
这是客户端代码,其中send是一个发送按钮,想按下后把文本域中的内容发出
且定义了 TextField serverMessage,clientMessage;和TextArea messageDisplay想把从服务器端的内容在messageDisplay上显示出来。可是老是失败。经过测试发现1,2处的打印语句始终不能运行。望高手能给我分析一下原因。谢谢先~~

客户端代码
public void runClient()
{
try
{
final Socket s=new Socket(InetAddress.getByName("localhost"),6000);
final OutputStream os=s.getOutputStream();
final InputStream is=s.getInputStream();

send.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{

String str=serverMessage.getText();

os.write(str.getBytes());
System.out.println(str);//-----------1

}
}

catch(IOException ioe){}
}
});

os.write("This is Client".getBytes());
byte[] buf=new byte[1024];
int length=is.read(buf);
messageDisplay.append(new String(buf,0,length));
os.close();
is.close();
s.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}


服务器端代码
public void runServer()
{
try
{
final ServerSocket ss=new ServerSocket(6000);//设置服务端口号
final Socket s=ss.accept();
final OutputStream os=s.getOutputStream();
final InputStream is=s.getInputStream();

send.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
String str=clientMessage.getText();
os.write(str.getBytes());
System.out.println(clientMessage.getText());//-----------------2

}
catch(IOException ioe){}
}
});

os.write("This is Server".getBytes());
byte[] buf=new byte[1024];
int length=is.read(buf);
messageDisplay.append(new String(buf,0,length));

os.close();
is.close();
s.close();
ss.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
...全文
127 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
for_cyan 2007-09-19
  • 打赏
  • 举报
回复
首先确保发送数据前,客户端已经连上了服务器,测试数据是否有发送,服务器端是否有接受
sszhangy 2007-09-19
  • 打赏
  • 举报
回复
write之后加一个flush()函数试试
aaa2003gf 2007-09-19
  • 打赏
  • 举报
回复
找本书重新研究下流的处理.

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧