这是客户端
package com.yzb;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.AncestorListener;
public class ChatClient extends JFrame {
JTextArea jta = new JTextArea();
JTextField jtf = new JTextField();
Socket s = null;
//PrintWriter pw = null;
DataOutputStream dos= null;
public ChatClient() {
super();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
ChatClient.this.disConnect();
System.exit(0);
}
});
this.getContentPane().add(jta, "Center");
pack();// 调整此窗口的大小,以适合其子组件的首选大小和布局。
this.getContentPane().add(jtf, "South");
jtf.addActionListener(new JTFListener());
}
private class JTFListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String str = jtf.getText().trim();
jta.setText(str);
jtf.setText("");
/*pw.write(str);
pw.flush();
pw.close();*/
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
ChatClient Chat = new ChatClient();
Chat.setLocation(100, 100);
Chat.setSize(300, 300);
Chat.setVisible(true);
Chat.connect();
}
public void connect() {
try {
s = new Socket("127.0.0.1",8001);
dos = new DataOutputStream(s.getOutputStream());
//pw = new PrintWriter(s.getOutputStream());
System.out.println("Connected");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disConnect(){
//pw.close();
try {
dos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是服务器
package com.yzb;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
public static void main(String[] args) {
boolean started = false;
try {
ServerSocket ss = new ServerSocket(8001);
started = true;
while(started){
boolean bConnect = false;
Socket s = ss.accept();
System.out.println("a client is connect");
bConnect = true;
InputStream is = s.getInputStream();
//BufferedReader br = new BufferedReader(new InputStreamReader(is));
//System.out.println(br.readLine());
DataInputStream dis = new DataInputStream(is);
while(bConnect){
System.out.println(dis.readUTF());
}
//br.close();
s.close();
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|