这事client端
public class ChatClient extends Frame {
Socket s = null;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
System.out.println("connected!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
taContent.setText(str);
tfTxt.setText("");
try {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
dos.flush();
dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
这事server端 为什么不能重复接收 只是一个本地聊天软件
public class ChatServer {
public static void main(String[] args) {
boolean started = false;
try {
ServerSocket ss = new ServerSocket(8888);
started = true;
while(started) {
boolean bConnected = false;
Socket s = ss.accept();
bConnected = true;
DataInputStream dis = new DataInputStream(s.getInputStream());
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
}
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|