JAVA编程实现多人聊天室

学习Java网络编程也有点久了,下面实现一个常见的小应用–多人聊天室

使用JAVA编程实现多人聊天室(需要用到多线程),服务器端包含如下功能:
(1) 若有新用户连接,则向已经连接到服务端的用户发送用户上线消息。
(2) 若有用户断开连接,则向在线用户发送用户下线消息。
(3) 若有用户发送消息,则向所有用户转发该消息。
(4) 当停止服务时,断开所有用户连接。

客户端代码:

package server;

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatClient {
	DataInputStream in = null;
	DataOutputStream out = null;
	Socket mysocket = null;
	
	public static void main(String args[]) {
		ChatClient chatClient = new ChatClient();
		chatClient.init();
	}
	
	public void init() {
		@SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
		try {
			mysocket = new Socket("127.0.0.1", 8090);
			Thread thread = new Thread(new SentToServer());
			System.out.print("客户端");
			in = new DataInputStream(mysocket.getInputStream());
			out = new DataOutputStream(mysocket.getOutputStream());
			
			thread.start();
			String message=null;
			while (true) {
				try {
					 message= scanner.next();
					out.writeUTF(message);
					out.flush();
				} catch (Exception e) {
				
				}
			}
		} catch (Exception e) {
			System.out.println("服务器开没开启!" );
		}
	}
	private class SentToServer implements Runnable {
		public void run() {
			try {
				while (true) {
					String str = in.readUTF();
					 System.out.println(str);
				}
			} catch (SocketException e) {
				System.out.println("服务器已关闭!");    //告诉用户服务器断开
				return;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

服务器端代码:

package server;
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
	private  List clients = new ArrayList();// 用于添加用户
	private static int clientNumber=1;
	
	public static void main(String args[]) {
		ChatServer chatServer = new ChatServer();
		chatServer.init();
	}
	@SuppressWarnings("resource")
	public void init() {
		ServerSocket server = null;
		Socket socket = null;
		try {
			server = new ServerSocket(8090);
			System.out.println("*************服务端***************");
	        System.out.println("服务器已经开启,端口8090等待被连接");
		} catch (IOException e1) {
			System.out.println("该端口正在监听!");         // ServerSocket对象不能重复创建
			return;
		}
		
		while (true) {
			try {
				socket = server.accept();
				System.out.println(" 用户Client"+clientNumber+"连上");
			} catch (IOException e) {
				System.out.println("用户连接失败");
			}
			if (socket != null) {
				Client client = new Client(socket);
				clientNumber++;
				clients.add(client);
				client.start();
			}
		}
	}

	private class Client extends Thread {
		@SuppressWarnings("unused")
		Socket socket = null;
		DataOutputStream out = null;
		DataInputStream in = null;
		String message = null;
		String name = null;

		Client(Socket socket) {
			name = "client"+clientNumber;
			this.socket = socket;
			try {
				out = new DataOutputStream(socket.getOutputStream());
				in = new DataInputStream(socket.getInputStream());
			} catch (IOException e) {
				System.out.println("服务器已经断开!");
			}
		}

		public void run() {
			sendToEveryClient(this.name);     
			for (int i = 0; i < clients.size(); i++) {         // 将信息发往每个用户我上线了
				Client client = clients.get(i);
				if(!client.equals(this))
					client.sendToEveryClient(this.name+"上线了");
				
				if(client.equals(this)) {
					for (int j = 0; j < clients.size()-1; j++) {            // 将信息发往刚上线的用户谁在线了(除了自己
						Client clienta = clients.get(j);
						client.sendToEveryClient(clienta.name+"在线上了!");
					}
				}
			}
			try {
				while (true) {
					message = in.readUTF();
					for (int i = 0; i < clients.size(); i++) {              // 将信息发往每个用户(除了自己
						Client client = clients.get(i);
						if(!client.equals(this)) {
							client.sendToEveryClient(this.name+":"+message);
						}
					}
				}
			} catch (IOException e) {
				System.out.println(this.name+"客户离开");
				for (int i = 0; i < clients.size(); i++) {             // 将信息发往每个用户我下线了
					Client client = clients.get(i);
					if(!client.equals(this))
						client.sendToEveryClient(this.name+"离开了");
				}
			}
		}
		
		public void sendToEveryClient(String str) {    // 将信息发送到每一位用户
			try {
				out.writeUTF(str);
				out.flush();
			} catch (IOException e) {
				clients.remove(this);       //用户退出
			}
		}
	}
}

结果截图如下:
JAVA编程实现多人聊天室_第1张图片

JAVA编程实现多人聊天室_第2张图片

你可能感兴趣的:(java)