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

📄 chatserver.java

📁 ChipChat实现的是局域网中的聊天功能
💻 JAVA
字号:
package com.itjob.chat;

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

public class ChatServer {

	/**
	 * @param args
	 */
	private ServerSocket ss;
	private Socket s;
	private List<Client> clients = new ArrayList<Client>();

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

	private class Client implements Runnable {
		Socket s;
		DataInputStream dis;
		DataOutputStream dos;
		String str = null;
		Client c;
		boolean isGetInputStream = false;

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

		public void run() {
			acceptMessage();
		}
		
		private void acceptMessage() {
			try {
				while (isGetInputStream) {
					str = dis.readUTF();
					for(int i = 0; i < clients.size(); i++){
						c = clients.get(i);
						c.sendMessage(str);
					}
					System.out.println(str);
				}
			} catch (EOFException e) {
				System.out.println("客户端已关闭!");
			} catch (SocketException e){
				System.out.println("客户端已关闭!");
			} catch (IOException e) {
				System.out.println("读取消息异常!");
				e.printStackTrace();
			} finally {
				try {
					if (dis != null)
						dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	
		private void sendMessage(String str) {
				try {
					dos.writeUTF(str);
					dos.flush();
				} catch(SocketException e){
					clients.remove(this);
					System.out.println("A Client closed!");					
				} catch (IOException e) {

					e.printStackTrace();
				}
		}
	}

	public void start() {
		boolean isStartServer = false;
		try {
			ss = new ServerSocket(5555);
			isStartServer = true;
			while (isStartServer) {
				s = ss.accept();
				Client ct = new Client(s);
				new Thread(ct).start();
				clients.add(ct);
				System.out.println("a client connected!");// --
			}
		} catch (BindException e) {
			System.out.println("端口已经被占用,查看你是否已经启动了一个该服务!");
		} catch (IOException e) {
			System.out.println("服务启动失败!");
		} finally {
			try {
				if(s!=null){
					s.close();
				}
				if(ss!=null){
					ss.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.exit(0);
		}
	}
}

⌨️ 快捷键说明

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