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

📄 chatserver.java

📁 本人大二学习汇编语言程序设计时的全部源代码
💻 JAVA
字号:
package com.paradise.chat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ChatServer {

	private boolean isStarted = false;
	private ServerSocket ss = null;
	List<Client> clients = new ArrayList<Client>();	
	private int clientId = 0;
	
	public void start() {
		try {
			ss = new ServerSocket(2008);
			isStarted = true;
			System.out.println("Server start!");
		} catch (BindException e) {
			System.out.println("the port is being used...");
			System.out.println("please close other applications and restart CharServer");
			System.exit(0);
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			while (isStarted) {
				Socket s = ss.accept();
				Client c = new Client(s);
				System.out.println("a client connected!");
				new Client(s).start();
				clients.add(c);
				clientId++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(ss != null) {
					ss.close(); 
					ss = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

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

	
	class Client extends Thread {
		
		private Socket s = null;
		private DataInputStream dis = null;
		private DataOutputStream dos = null;
		private boolean isConnected = false;
		
		public Client(Socket s) {
			this.s = s;
			try {
				dis = new DataInputStream(s.getInputStream());
				dos = new DataOutputStream(s.getOutputStream());
				isConnected = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		public void send (String str) {
			try {
				dos.writeUTF(str);
			} catch (IOException e) {
				clients.remove(this);
				System.out.println("a client exit! I have remove it from List");
				//e.printStackTrace();
			}
		}

		public void run() {
			try {
				while (isConnected) {
					String str = dis.readUTF();
					for(int i = 0; i<clients.size(); i++ ) {
						Client c = clients.get(i);
						c.send(str);
						System.out.println("a string send");
					}
				}
			} catch (SocketException e) {
				System.out.println("Client exit!");
			} catch (EOFException e) {
				System.out.println("Client closed!");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(dis != null) dis.close();
					if(dos != null) dos.close();
					if(s != null) {
						s.close();
						s = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

⌨️ 快捷键说明

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