⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatserver.java

📁 利用Socket编写的java聊天程序
💻 JAVA
字号:
/*
 * version 0.4
 * 添加Server端
 */

/*
 * version 0.5
 * 添加接收客户端的一句话的功能
 */

/*
 * version 0.6
 * 连续接收Client端的信息
 */

/*
 * version 0.7
 * 修正Client关闭时Server端的java.io.EOFException异常
 * 出现该异常主要原因是资源没有释放
 */

/*
 * version 0.8
 * 使用多线程让多个Client可以连接到Server
 * 使用Client线程类实现
 */

/*
 * version 0.9
 * 将Server端接收到的数据发送到各个Client端
 */

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

public class ChatServer {

	ServerSocket ss = null; 
	
	boolean isStarted = false;
	
	List<Client> clients = new ArrayList<Client>();

	public static void main(String[] args) {
		new ChatServer().start();
	}

	private void start() {

		// 启动Server监听
		try {
			ss = new ServerSocket(8888);
			isStarted = true;
		} catch (BindException e) {
			System.out.println("端口使用中......");
			System.out.println("请重启有关程序");
			System.exit(0);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 处理Client的连接
		try {
			while(isStarted){
				Socket socket = ss.accept();
				Client c = new Client(socket);
				new Thread(c).start();
				clients.add(c);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 处理Client的Client线程类
	private class Client implements Runnable {

		boolean isConnected = false;

		Socket socket = null;

		DataInputStream dis = null;

		DataOutputStream dos = null;

		public Client(Socket socket) {
			this.socket = socket;
			isConnected = true;
			try {
				dis = new DataInputStream(socket.getInputStream());
				dos = new DataOutputStream(socket.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {
			try{
				while(isConnected){
					String str = dis.readUTF();
					System.out.println(str);
					
					//向各个Client端发送数据
					for(int i=0;i<clients.size();i++){
						Client c = clients.get(i);
						c.send(str);
					}
				}
			} catch( EOFException e){
				System.out.println("a client was disconnected!");
			} catch(IOException e){
				e.printStackTrace();
			}
		}
		
		//发送信息到Client
		public void send(String str){
			try {
				dos.writeUTF(str);
			} catch (IOException e) {
				clients.remove(this);
				System.out.println("a client quit!");
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -