---
title: "Java 聊天器 (多线程模型)"
author: "leoizumi"
date: "2010-01-17T17:18:25Z"
tags: [".net", "Java", "Socket", "thread", "多线程"]
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2010-01-17T17:18:25Z"
id: 572791
url: "https://lihaoquan.iteye.com/blog/572791"
---

```
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;


public class ChatServer {
	boolean started = false;
	ServerSocket serverSocket = null;
	
	public static void main(String[] args) {
		new ChatServer().start();
	}
	
	public void start() {
		try {
			serverSocket = new ServerSocket(7777);
			started = true;
		}
		catch(BindException e2) {
			System.out.println("端口使用中 ... ...");
			System.out.println("请关闭双关程序!");
			System.exit(0);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		try{
			while(started) {
			    Socket socket = serverSocket.accept();
			    Client client = new Client(socket);
				System.out.println("连接上了... ...");
				new Thread(client).start();
			}
		} catch (IOException e) {
			System.out.println("Server 关闭");
		}finally {
	          try {
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}	
	}

	class Client implements Runnable {

		private Socket socket;
		private DataInputStream dis = null;
		boolean bConnected = false;
		
		public Client(Socket socket) {
			this.socket = socket;
		
			try {
				dis = new DataInputStream(socket.getInputStream());
				bConnected = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		public void run() {
			try{
          	while(bConnected) {
          		String str = dis.readUTF();
          		System.out.println(str);
          	}	
			}catch (EOFException e) {
				System.out.println("Server 关闭");
			}catch(IOException e) {
				e.printStackTrace();
			}finally {
				try {
					if(dis != null)dis.close();
					if(socket != null)socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		
	}
	
}
```