简单的聊天程序(java的socket+多线程)

服务端
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ServerTest {
	//创建一个ServerSocket,用于监听客户端Socket连接请求
	ServerSocket server = null;
	
	//装多个客户端的容器
	Collection clients = new ArrayList();
	
	public ServerTest(int port) throws Exception {
		server = new ServerSocket(port);
	}
	
	//可接受多个客户端连接
	public void startServer() throws Exception {
		System.out.println("服务器启动中...");
		while (true) {
			//侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞
			Socket s = server.accept();
			
			clients.add(new ClientProcess(s));
			
			System.out.println("NewClient" + s.getInetAddress() + ":" + s.getPort());
			System.out.println("ClientCount: " + clients.size() + "\n");
			
		}
	}
	
	class ClientProcess implements Runnable {
		
		Socket s = null;
		
		public ClientProcess(Socket s) {
			this.s = s;
			//启动线程
			(new Thread(this)).start();
		}
		//发送消息给客户端
		public void send(String str) throws IOException {
			DataOutputStream dos = new DataOutputStream(s.getOutputStream());
			dos.writeUTF(str);
		}
		//获取客户端发来的消息
//		public String getMessage() throws Exception {
//			DataInputStream dis = new DataInputStream(s.getInputStream());
//			String str = dis.readUTF();
//			return str;
//		}
		
		//释放socket并移除断开的客户端
		public void destory() {
			try {
				if (s != null) s.close();
				clients.remove(this);
				System.out.println("A client out!");
				System.out.println("ClientCount: " + clients.size() + "\n");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		//继续监听是否有消息发来
		public void run() {
			
			try {
				DataInputStream dis = new DataInputStream(s.getInputStream());
				String str = null;
				
				while (true) {
					//没收到消息来该方法会阻塞
					str = dis.readUTF();
					System.out.println(s.getInetAddress() + "-" + s.getPort() + ": " + str);
					//消息共享到多个客户端
					for (Iterator it = clients.iterator(); it.hasNext();) {
						
						ClientProcess cp = (ClientProcess) it.next();
						
						if (this != cp) {
							cp.send(s.getInetAddress() + "-" + s.getPort() + ": " + str);
						}
						
					}
				}
				
			} catch (Exception e) {
				//客户端退出后触发
				System.out.println("Client quit");
				this.destory();
			}
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		ServerTest st = new ServerTest(8888);
		st.startServer();
	}
	
}
客户端
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class ChatClient extends Frame {
	TextArea ta = new TextArea();
	TextField tf = new TextField();
	Socket s = null;
	
	public void launchFrame() throws Exception {
		this.add(ta, BorderLayout.CENTER);
		this.add(tf, BorderLayout.SOUTH);
		tf.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent ae) {
					try {
						String sSend = tf.getText();
						if (sSend.trim().length() == 0) {
							System.out.println("输入为空!");
							return;
						}
						ChatClient.this.send(sSend);
						tf.setText("");
						ta.append("me: " + sSend + "\n");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		);
		
		this.addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					System.exit(0);
				}
			}
		);
		setBounds(300,300,300,400);
		setVisible(true);
		ta.requestFocus();
	}
	
	
	
	public ChatClient() throws Exception {
		s = new Socket("39.108.12.42", 9050);
		launchFrame();
		(new Thread(new ReceiveThread())).start();
	}
	//向服務器發送數據
	public void send(String str) throws Exception {
		DataOutputStream dos = new DataOutputStream(s.getOutputStream());
		dos.writeUTF(str);
	}
	
	public void disconnect() throws Exception {
		s.close();
	}
	

	
	class ReceiveThread implements Runnable {
		public void run() {
			
			if (s == null) return;
			try {
				DataInputStream dis = new DataInputStream(s.getInputStream());
				String str = dis.readUTF();
				while (str != null && str.length() != 0) {
					//System.out.println(str);
					ChatClient.this.ta.append(str + "\n");
					str = dis.readUTF();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		ChatClient cc = new ChatClient();
	}
}

猜你喜欢

转载自blog.csdn.net/ZWHSOUL/article/details/82940770