1.服务器连接

package com.wxh.chatroom;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class ServerConnection extends Thread{
private Socket socket;
private PrintWriter pw;
private BufferedReader br;

public ServerConnection(Socket socket) {
super();
this.socket = socket;
// 直接开启线程
this.start();
}

// 发送信息的方法
public void send(String msg) {
// 使用socket将msg写出去
try {
if (pw == null) {
pw = new PrintWriter(socket.getOutputStream());
}
// 输出信息
pw.println(msg);
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}

// 关闭socket
public void disConnect() {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
}
}
}

// 接收功能(线程)
public void run() {
// 不断读取服务器数据
try {
if (br == null) {
br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
String msg = null;
while ((msg = br.readLine()) != null) {
System.out.println(msg);

// 转发
Set<Map.Entry<String, ServerConnection>> entrySet = DB.connMap
.entrySet();

Iterator<Map.Entry<String, ServerConnection>> ite = entrySet
.iterator();
while (ite.hasNext()) {
Map.Entry<String, ServerConnection> entry = ite.next();
ServerConnection conn = entry.getValue();
conn.send(socket.getInetAddress() + ":" + msg);
}
}
} catch (SocketException e) {
System.out.println("下线了");
} catch (IOException e) {
e.printStackTrace();
}
}
public String getIp() {
return this.socket.getInetAddress().getHostAddress();
}
}


2.保存connection

package com.wxh.chatroom;

import java.util.HashMap;
import java.util.Map;

/**
* 保存connection
* @author Administrator
*
*/
public class DB {
public static Map<String,ServerConnection> connMap=new HashMap<String,ServerConnection>();

public static void add(ServerConnection conn){
connMap.put(conn.getIp(), conn);
}
}


3.聊天室服务器端

package com.wxh.chatroom;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatRoomServer {

public static void main(String[] args) {
ServerConnection connection = null;
try {
// 创建ServerSocket
ServerSocket serverSocket = new ServerSocket(9090);
// 等待客户端连接
boolean flag = true;
while (flag) {
Socket socket = serverSocket.accept();
System.out.println(socket.getInetAddress() + "上线了");

connection = new ServerConnection(socket);
DB.add(connection);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disConnect();
}
}
}

}