在线聊天室的Java实现(功能比较弱)

自己用Java写的一个在线聊天室...功能不是很完善...供参考[@more@]

ChatServer.java这里是主调用部分

成都创新互联公司-专业网站定制、快速模板网站建设、高性价比克拉玛依网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式克拉玛依网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖克拉玛依地区。费用合理售后完善,十余年实体公司更值得信赖。

package com.darkblue;

/**

*

*@authorDarkBlue

*

*本程序用于实现聊天室的服务器

*/

import java.net.*;

import java.io.*;

publicclass ChatServerimplements Runnable{

private ServerSocketserver;//服务器socket

privatestaticintport = 8888;//监听端口号

privatestaticbooleanisShutDown =false;//没有停止

private ChatServer() {

try {

server =new ServerSocket(port);//创建一个服务器socket

}catch (IOException e) {

e.printStackTrace();

}

}

publicstaticvoid startService() {

ChatServer cs =new ChatServer();

Thread th =new Thread(cs);

th.start();

}

publicvoid run(){

try {

//循环等待客户端连接

while(!isShutDown){

Socket socket =server.accept();

//使用socket进行通信

new SocketManager(socket).start();//开始一个线程

}

}catch (IOException e) {

e.printStackTrace();

}

}

publicstaticvoid stopService() {

isShutDown =true;

}

publicstaticvoid main(String[] args){

ChatServer.startService();

}

}

SocketManager.java 用于管理socket

package com.darkblue;

import java.net.*;

import java.io.*;

import java.util.*;

publicclass SocketManagerextends Thread {

privatestatic ListsocketList =new ArrayList();//存放socket

privatestatic Queuemessages =new LinkedList();//消息队列

private Socketsocket =null;//对象变量

public SocketManager() {

super();

}

public SocketManager(Socket socket) {

this.socket = socket;

addSocket(socket);

}

publicstaticvoid addSocket(Socket socket) {//增加一个socket

socketList.add(socket);

}

publicstaticvoid addMessage(String message) {

messages.add(message);

}

publicstaticvoid sendAllMessage() {

if (messages !=null) {

while (!messages.isEmpty()) {

Object msg =messages.remove();

if (msginstanceof 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();

}

}

}

}

}

}

}

publicvoid 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();

}

}

}

}


本文标题:在线聊天室的Java实现(功能比较弱)
分享URL:http://pwwzsj.com/article/jecogj.html