Client:
package Chat;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Client {
JTextArea jta;
JTextField jtf;
BufferedReader in;
PrintWriter out;
private void initGui(){
JFrame f=new JFrame("Client");
f.setSize(400,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jta=new JTextArea();
jta.setEditable(false);
f.add(new JScrollPane(jta));
jtf=new JTextField();
f.add(jtf,"South");
f.setVisible(true);
jtf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
String text=jtf.getText();
jtf.setText("");
out.println(text);
out.flush();
}
});
}
private void initNet(){
try {
Socket s=new Socket("127.0.0.1",8888);
out=new PrintWriter(s.getOutputStream());
in=new BufferedReader(
new InputStreamReader(s.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
}
private void receive(){
try {
while(true){
String str = in.readLine();
if(str==null){
return ;
}
jta.append("说"+str+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public Client(){
initGui();
initNet();
}
public static void main(String[] args) throws Exception{
Client c=new Client();
c.receive();
}
}
Server:
package ChatIV;
import java.net.*;
import java.io.*;
import java.util.*;
public class Server {
public static void main(String args[]){
try {
ServerSocket ss = new ServerSocket(8888);
List sockets = new ArrayList();
while(true){
Socket s = ss.accept();
sockets.add(s);
Thread t1 = new ChatThread(s,sockets);
t1.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ChatThread extends Thread{
Socket s;
List sockets;
public ChatThread(Socket s,List sockets){
this.s=s;
this.sockets=sockets;
}
public void run(){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while(true){
String str = in.readLine();
for(int i=0;i<sockets.size();i++){
Socket s2 = (Socket)sockets.get(i);
PrintWriter out = new PrintWriter(s2.getOutputStream());
out.println(str);
out.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}