Java 在线多客户端聊天 J2SE小练习

server端


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;

public class ChatSever {

	ArrayList<Client> clients = new ArrayList<Client>();

	public static void main(String[] args){
		new ChatSever().start();
	}

	void start(){
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(8081);
		} catch (IOException e) {
			System.out.println("端口已经被占用...");
			return ;
		}
		while (true) {
			Socket s = null;
			try {
				s = ss.accept();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Client c = new Client(s);
			clients.add(c);
			new Thread(c).start();
		}
	}

	class Client implements Runnable {
		private Socket s = null;
		DataInputStream dis = null;
		DataOutputStream dos = null;
		Client c=null;

		Client(Socket s){
			this.s = s;
			try {
				dis = new DataInputStream(s.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				dos = new DataOutputStream(s.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void sentAll(String str){
			try {
				dos.writeUTF(str);
			} catch (SocketException e) {
				if(c!=null)
					clients.remove(c);
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
		
		public void run() {
			try {
				while (true) {
					String receive = dis.readUTF();
					System.out.println(receive);
					// 转发
					for(int i=0;i<clients.size();i++){
						c=clients.get(i);
						c.sentAll(receive);
					}
				}
			} catch (SocketException e) {
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

Client端


import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatClient extends Frame {

	TextField txf = new TextField();
	TextArea txa = new TextArea();
	Socket s = null;
	DataOutputStream dos = null;
	DataInputStream dis = null;
	final String name = "user" + (int) (Math.random() * 100);

	public static void main(String[] args) {
		ChatClient cc = new ChatClient();
		cc.launchFrame();
		new Thread(cc.new RecvThread()).start();
	}

	public void launchFrame() {
		this.setTitle("Chat");
		this.setLocation(400, 300);
		this.setSize(300, 400);
		txa.setText("Let's Talk !");
		txf.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				sendToServer(txf.getText());
				txf.setText("");
			}

		});

		this.add(txa, BorderLayout.NORTH);
		this.add(txf, BorderLayout.SOUTH);
		this.pack();

		this.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent arg0) {
				sendToServer("我下线了!");
				setVisible(false);
				System.exit(0);
			}

		});
		this.setVisible(true);
		this.connect();
		sendToServer("我上线啦!");
	}

	public void connect() {
		try {
			s = new Socket("127.0.0.1", 8081);
		} catch (ConnectException e) {
			txa.setText(txa.getText() + "\n" + "连接服务器失败...");
			return;
			// e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			dos = new DataOutputStream(s.getOutputStream());
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (NullPointerException e1) {
			// e1.printStackTrace();
		}

		try {
			dis = new DataInputStream(s.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}catch (NullPointerException e) {
			//e.printStackTrace();
		}
	}
	
	private void sendToServer(String str){
		SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss");
		String send = f.format(new Date()) + "\n" + name + " : "
				+ str;
		try {
			dos.writeUTF(send);
			dos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			txa.setText(txa.getText() + "\n" + send + "  发送失败...");
			txf.setText("");
			//e.printStackTrace();
		}
	}


	class RecvThread implements Runnable {
		public void run() {
			try {
				while (true) {
					String recv = dis.readUTF();
					txa.setText(txa.getText() + "\n" + recv);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				//e.printStackTrace();
			}
		}
	}
	
}



你可能感兴趣的:(java,String,socket,J2SE,dos,聊天)