客户端:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatWindow extends Frame{
TextField tf=new TextField();
TextArea ta=new TextArea();
DataOutputStream dos=null;
Socket s=null; public static void main(String[] args) {
new ChatWindow().launchFrame();
}
public void launchFrame(){
setLocation(100,100);
setSize(300,300);
add(tf,BorderLayout.SOUTH);
add(ta,BorderLayout.NORTH);
pack();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
unconnect();
}
});
tf.addActionListener(new Monitor());
connect();
setVisible(true);
}
public void connect(){
try {
s=new Socket("127.0.0.1",8888);
dos=new DataOutputStream(s.getOutputStream());
System.out.println("connected!");
} catch (UnknownHostException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}
public void unconnect(){
try {
dos.close();
s.close();
} catch (IOException e) {

e.printStackTrace();
}
}
public class Monitor implements ActionListener{
public void actionPerformed(ActionEvent k) {
String m=tf.getText();
ta.setText(m);
tf.setText("");
try{
dos.writeUTF(m);
dos.flush();
} catch (IOException e) {

e.printStackTrace();
}

}

}
}
服务器:
import java.io.*;
import java.net.*;public class ServerWin { public static void main(String[] args) {
try {
ServerSocket ss=new ServerSocket(8888);
Socket s=ss.accept();
System.out.println("A has client!");
DataInputStream dis=new DataInputStream(s.getInputStream());
String str= dis.readUTF();
System.out.println(str);
dis.close();
} catch (IOException e) {

e.printStackTrace();
} }}
为什么运行时,客户端发出的信息不能在服务器端显示呢

解决方案 »

  1.   

    服务器端的代码应该包含在一个while语句中,否则执行一次accept,而此时没有客户端输入,等有客户端输入的时候服务器端已不再执行accept,所以不能接收客户端输入
      

  2.   

    第一次是可以显示的!因为你读一次数据,服务器就关闭了!如果你想读多次的话,就用while循环咯!
      

  3.   

    谢谢各位了,这个问题已经解决了,是自己用eclipse不熟的问题,还有就是这个就是这个程序现在就做到只接受一个个客户端的一条信息,还没做到后面呢。谢谢了,以后又不会的希望还能请教各位。