java基于TCP的聊天室

服务端

package com.net.chat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 聊天室,服务端
 *
 *
 */
public class Server {
	public static CopyOnWriteArrayList<Channel> clients;

	public static void main(String[] args) {
		clients = new CopyOnWriteArrayList<>();
		ServerSocket serverSocket = null;
		boolean isRunning = true;
		try {
			serverSocket = new ServerSocket(6666);
			while (isRunning) {
				Socket client = serverSocket.accept();
				System.out.println("一个客户端连接了");
				Channel channel = new Channel(client);
				clients.add(channel);
				new Thread(channel).start();
			}
		} catch (IOException e) {
			isRunning = false;
			System.out.println("服务端创建失败");
		}
		try {
			if (serverSocket != null) {
				serverSocket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	static class Channel implements Runnable {
		private Socket client;
		private DataInputStream dis;
		private DataOutputStream dos;
		private boolean isRunning;
		private String name;

		public Channel(Socket client) {
			super();
			this.client = client;
		}

		@Override
		public void run() {
			String mString = "";
			isRunning = true;
			this.name = this.receive();
			sendOthers("欢迎" + this.name + "光临聊天室", true);
			while (isRunning) {
				mString = this.receive();
				sendOthers(mString, false);
			}
			// 如果断开
			sendOthers(this.name + "离开了聊天室", true);
		}

		public String receive() {
			String msg = "";
			try {
				dis = new DataInputStream(client.getInputStream());
				msg = dis.readUTF();
			} catch (IOException e) {
				System.out.println("接收数据失败");
				isRunning = false;
				this.release();
			}
			return msg;
		}

		public void send(String msg) {
			try {
				dos = new DataOutputStream(client.getOutputStream());
				dos.writeUTF(msg);
				dos.flush();
			} catch (IOException e) {
				isRunning = false;
				System.out.println("发送数据失败");
				this.release();
			}
		}

		// 群聊
		public void sendOthers(String msg, boolean isSys) {
			// 私聊,规定发送格式@name:msg
			if (msg.startsWith("@")) { // 如果已@开头
				// 截取name
				int index = msg.indexOf(":");
				String name = msg.substring(1, index);
				msg = msg.substring(index + 1);
				for (Channel client : clients) {
					if (client.name.equals(name)) {
						client.send(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " " + this.name
								+ "悄悄地对你说:");
						client.send(msg);
					}
				}

			} else {
				if (isSys) {
					for (Channel client : clients) {
						if (client != this) {
							client.send(msg);
						}
					}
				} else { // 如果不是系统消息,输出名字
					for (Channel client : clients) {
						if (client != this) {
							client.send(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " " + this.name
									+ ":");
							client.send(msg);
						}
					}
				}
			}
		}

		public void release() {
			ChatUtils.release(dis, dos, client);
		}
	}
}

客户端

package com.net.chat;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 客户端
 *
 */
public class Client {
	public static void main(String[] args) {
		Socket client = null;
		try {
			client = new Socket("localhost",6666);
			new Thread(new Send(client)).start();
			new Thread(new Receive(client)).start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
class Send implements Runnable{
	private DataOutputStream dos;
	private BufferedReader reader;
	private Socket client;
	private boolean isRunning;
	
	public Send(Socket client) {
		super();
		this.client = client;
	}

	@Override
	public void run() {
		reader = new BufferedReader(new InputStreamReader(System.in));
		String mString = "";
		isRunning = true;
		System.out.println("请输入你的名字:");
		try {
			String name = reader.readLine();
			this.send(name);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		try {
			while(isRunning) {
				mString = reader.readLine();
				this.send(mString);
			}
		} catch (IOException e) {
			isRunning = false;
			this.release();
		}
	}
	
	public void send(String msg) {
		try {
			dos = new DataOutputStream(client.getOutputStream());
			dos.writeUTF(msg);
			dos.flush();
		} catch (IOException e) {
			this.release();
		}
		
	}
	
	public void release() {
		ChatUtils.release(dos,client);
	}
}

class Receive implements Runnable{
	private DataInputStream dis ;
	private Socket client;
	private boolean isRunning;
	
	public Receive(Socket client) {
		super();
		this.client = client;
	}


	@Override
	public void run() {
		isRunning = true;
		while(isRunning) {
			this.receive();
		}
	}
	
	public void receive() {
		String mString = "";
		try {
			dis = new DataInputStream(client.getInputStream());
			mString = dis.readUTF();
			if (!mString.equals("bye")) {
				System.out.println(mString);
			}else {
				System.exit(0);
			}
		} catch (IOException e) {
			
			this.release();
		}
	}
	
	public void release() {
		ChatUtils.release(dis,client);
	}
}

你可能感兴趣的:(learning)