要实现的功能就是:同时打开多个客户端,并在输入窗口中发送的消息,在服务器上打印。(问题:在服务器上无法打印出客户端内容)客户端:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class ChatClient extends Frame {
  TextArea ta = new TextArea();
  TextField tf = new TextField();
Socket s = null;
DataOutputStream dos = null;

public static void main(String[] args) {
new ChatClient().launchFrame();
}
//创建输入界面,并添加监听器
public void launchFrame() {
setLocation(400,400);
this.setSize(300,500);
add(ta,BorderLayout.CENTER);
add(tf,BorderLayout.SOUTH);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
                disconnected();
System.exit(0);
}
});
tf.addActionListener(new TfListener());
setVisible(true);
connected();
}
//连接服务器端口
public void connected(){
try {
 s = new Socket("127.0.0.1",8869);
     dos = new DataOutputStream(s.getOutputStream());
System.out.println("connected");      
     
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//断开服务器端口
public void disconnected(){
try {
dos.close();
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//行为事件
    private class TfListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
   String str = tf.getText().trim();
   ta.setText(str);
   tf.setText("");
   try{
    dos.writeUTF(str);
dos.flush();
    }catch(IOException e1){
     e1.printStackTrace();
    }
   }
    }
}
服务器:
import java.io.*;
import java.net.*;public class ChatServer { boolean started = false;
ServerSocket ss = null; public static void main(String[] args) {
   new ChatServer().start();
}
//服务器端口启动
public void start() {
try {
ss = new ServerSocket(8869);
started = true;
} catch (BindException e) {
System.out.print("端口使用中");
//System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (started) {
Socket s = ss.accept();
Client c = new Client(s);
new Thread(c).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
//多线程同时接受多个客户端
class Client implements Runnable {
private Socket s;
String str = null;
private DataInputStream dis = null;       // private String str = null;

private boolean bConnected = false; public Client(Socket s) {
this.s = s; try {
dis = new DataInputStream(s.getInputStream());
bConnected = true; } catch (IOException e) {
e.printStackTrace();
} } public void run() {
try {
while (bConnected)
str = dis.readUTF();
System.out.println(str);
} catch (EOFException e) {
System.out.print("windows closed");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null)
dis.close();
if (s != null)
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} }
}