基于TCP/IP的网络聊天室实现(复杂--多人聊天)

基于TCP/IP的网络聊天室实现(复杂--多人聊天)_第1张图片
服务器端:

/**
 * 内网通
 * @author mrchai
 */
public class SQServer {
	
	/**对外提供服务端口号*/
	private int port;
	/**用于记录所有产生Socket对象*/
	public volatile static List<Socket> clients = new ArrayList<>();
	
	public SQServer(int port) {
		super();
		this.port = port;
	}

	public void startServer() {
		try {
			//创建服务
			ServerSocket server = new ServerSocket(port);
			Tools.tips("服务已开启,等待连接...");
			while(true) {
				//监听客户端连接
				Socket s = server.accept();
				//将获取的Socket存储到集合中
				clients.add(s);
				Tools.tips("客户端已连接:"+Tools.ip(s));
				//启动聊天服务线程
				new TalkingServer(s).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		//启动服务
		new SQServer(8090).startServer();
		
	}
}

/**
 * 消息接收转发线程
 * @author mrchai
 *
 */
public class MsgServer extends Thread{

	private Socket s;
	
	public MsgServer(Socket s) {
		this.s = s;
	}

	@Override
	public void run() {
		try {
			//读取接收到的来自Socket消息
			//获取socket的输入流
			InputStream is = s.getInputStream();
			//将字节输入流转换为字符输入流
			InputStreamReader isr = new InputStreamReader(is);
			//将低级流转换为缓冲流
			BufferedReader br = new BufferedReader(isr);
			//临时变量用于接收每一次读取的文本消息
			String msg = null;
			while((msg = br.readLine()) != null) {
				//遍历每一个Socket对象
				for(Socket c:SQServer.clients) {
					
					//格式化消息内容(时间+发送人主机名+消息内容)
					String content = Tools.time(System.currentTimeMillis()) + Tools.host(s)+":"+msg;
					
					Tools.sendMsg(c.getOutputStream(), content); 
				}
			}
		} catch (Exception e) {
			//e.printStackTrace();
			Tools.tips("客户端断开连接:"+Tools.ip(s));
			//从集合中移除该对象
			SQServer.clients.remove(s);
		}
	}
}
/**
 * 聊天服务线程
 * @author mrchai
 */
public class TalkingServer extends Thread{

	private Socket s;
	
	public TalkingServer(Socket s) {
		this.s = s;
	}

	@Override
	public void run() {
		try {
			//发送欢迎消息给客户端
			Tools.sendMsg(s.getOutputStream(), "欢迎使用softeem内网通,聊得愉快!");
			//启动消息接收和转发线程
			new MsgServer(s).start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}

客户端:

/**
 * 聊天服务的客户端
 * @author mrchai
 *
 */
public class SQClient {

	/**远程服务器的ip地址*/
	private String ip;
	/**远程服务端应用的端口*/
	private int port;
	
	public SQClient(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}

	public void startChats() {
		try {
			Socket s = new Socket(ip,port);
			//启动消息接收线程
			MsgReceiver mr = new MsgReceiver(s);
			//设置消息接收线程为守护线程
			mr.setDaemon(true);
			mr.start();
			//获取文本扫描对象
			Scanner sc = new Scanner(System.in);
			OutputStream os = s.getOutputStream();
			String msg = "";
			while(!"quit".equals(msg)) {
				msg = sc.nextLine();
				Tools.sendMsg(os, msg);
			}
			System.out.println("结束聊天!");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		SQClient client = new SQClient("192.168.7.141", 8090);
		client.startChats();
	}

}

/**
 * 消息接收的线程
 * @author mrchai
 *
 */
public class MsgReceiver extends Thread{

	private Socket s;
	
	public MsgReceiver(Socket s) {
		this.s = s;
	}
	
	@Override
	public void run() {
		BufferedReader br = null;
		try {
			//获取socket中的字节输入流
			InputStream is = s.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			String msg = null;
			//循环读取
			while((msg = br.readLine()) != null) {
				Tools.tips(msg);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(br != null)br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

工具类:

public class Tools {

	/**
	 * 封装消息提示
	 * @param msg
	 */
	public static void tips(String msg) {
		System.out.println(msg); 
	}
	
	/**
	 * 封装ip转换
	 * @param s
	 * @return
	 */
	public static String ip(Socket s) {
		return s.getInetAddress().getHostAddress();
	}
	
	/**
	 * 封装主机名转换
	 * @param s
	 * @return
	 */
	public static String host(Socket s) {
		return s.getInetAddress().getHostName();
	}
	
	/***
	 * 
	 * 根据提供的毫秒时间转换为固定格式的时间
	 * HH:mm:ss
	 * @param t
	 * @return
	 */
	public static String time(long t) {
		//根据提供的时间毫秒数构建日期对象
		Date d = new Date(t);
		SimpleDateFormat sdf = new SimpleDateFormat("[HH:mm:ss]");
		return sdf.format(d);
	}
	
	/**
	 * 通过输出流发送文本消息
	 * @param os
	 * @param msg
	 */
	public static void sendMsg(OutputStream os,String msg) {
		PrintWriter pw = new PrintWriter(os);
		pw.println(msg);
		pw.flush();
	}
}

你可能感兴趣的:(java,网络,java)