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();
			}
		}
	}
	
}



  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值