ChatServer.java这里是主调用部分
package com.darkblue;
/**
*
* @author DarkBlue
*
* 本程序用于实现聊天室的服务器端
*/
import java.net.*;
import java.io.*;
public class ChatServer implements Runnable{
private ServerSocket server;// 服务器socket
private static int port = 8888;// 监听端口号
private static boolean isShutDown = false;//没有停止
private ChatServer() {
try {
server = new ServerSocket(port);// 创建一个服务器socket
} catch (IOException e) {
e.printStackTrace();
}
}
public static void startService() {
ChatServer cs = new ChatServer();
Thread th = new Thread(cs);
th.start();
}
public void run(){
try {
//循环等待客户端连接
while(!isShutDown){
Socket socket = server.accept();
//使用socket进行通信
new SocketManager(socket).start();//开始一个线程
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void stopService() {
isShutDown = true;
}
public static void main(String[] args){
ChatServer.startService();
}
}
SocketManager.java 用于管理socket
package com.darkblue;
import java.net.*;
import java.io.*;
import java.util.*;
public class SocketManager extends Thread {
private static List socketList = new ArrayList();// 存放socket
private static Queue messages = new LinkedList();// 消息队列
private Socket socket = null;// 对象变量
public SocketManager() {
super();
}
public SocketManager(Socket socket) {
this.socket = socket;
addSocket(socket);
}
public static void addSocket(Socket socket) {// 增加一个socket
socketList.add(socket);
}
public static void addMessage(String message) {
messages.add(message);
}
public static void sendAllMessage() {
if (messages != null) {
while (!messages.isEmpty()) {
Object msg = messages.remove();
if (msg instanceof String) {
String message = (String) msg;
if (socketList != null) {// 循环发送
for (int i = 0; i < socketList.size(); i++) {
Socket socket = (Socket) socketList.get(i);
try {
OutputStreamWriter osw = new OutputStreamWriter(
socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
bw.write(message + "nr");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
public void run() {// 针对每个socket进行
if (socket != null) {// socket不为null
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));//输入流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("欢迎使用本聊天系统nr");
bw.write("输入消息后按回车发送消息nr");
bw.write("消息:");
bw.flush();
String temp = br.readLine();//读取消息
while(temp!=null){
addMessage(temp);
sendAllMessage();
bw.write("消息:");
bw.flush();
temp=br.readLine();
}
br.close();
bw.close();
socket.close();
socketList.remove(socket);//移除
System.out.println("关闭了一个");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。