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

📄 chatserver.java

📁 使用java socket编程
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {

	boolean started = false;

	ServerSocket ss = null;

	List<Client> clients = new ArrayList<Client>();
	
	public static void main(String[] args) {
		new ChatServer().start();
	}

	void start() {
		try {
			ss = new ServerSocket(8888);
			started = true;
		} catch (BindException e) {
			System.out.println("端口使用中。。。");
			System.out.println("请关闭相应程序!");
			System.exit(0);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		try {
			while (started) {
				Socket s;
				s = ss.accept();
				Client c = new Client(s);
				clients.add(c);
				new Thread(c).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ss.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	class Client implements Runnable {

		private boolean bConnected = false;

		private DataInputStream dis = null;

		private DataOutputStream dos = null;
		
		private Socket s = null;
		Client(Socket s) {
			this.s = s;
			bConnected = true;
			try {
				dis = new DataInputStream(s.getInputStream());
				dos = new DataOutputStream(s.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void send(String str) {
			try {
				dos.writeUTF(str);
			} catch (IOException e) {
				clients.remove(this);
				System.out.println("One Client exits!");
			}
		}
		
		public void run() {
			System.out.println("A client connected!");
			try {
				while (bConnected) {
					String str = null;
					str = dis.readUTF();
System.out.println(str);
					for(int i = 0;i < clients.size();i ++) {
						clients.get(i).send(str);
					}
				}
			} catch (EOFException e) {
				System.out.println("A client is closed!");
			} catch (IOException e) {
				System.out.println("Error!");
				e.printStackTrace();
			} finally {
				try {
					/*
					 * 如果dis、s还没有初始化,就不要关闭它们 所以在关闭前先判断一下
					 */
					if (dis != null)
						dis.close();
					if (dos != null)
						dos.close();
					if (s != null)
						s.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

	}
}

⌨️ 快捷键说明

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