class ChatRoomServer
服务器端
package chatserver2;
//Chat Room Server
//this software is designed by Chen Heping(陈和平)
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatRoomServer extends Frame implements Runnable{
Panel panel;
ScrollPane sPanel;
TextArea textArea;
Button button1;
//net
ServerSocket serverSock;
public final static int DEFAULT_PORT=8080;//默认端口号
Thread chatAcceptThread;//启动接受连接的线程
BroadcastThread broadcastThread;//广播thread; run when server is listening
java.util.Vector clients;//记录连接的线程
java.util.Vector clientsInfor;//记录连接线程的信息
public static int index=0;
public ChatRoomServer(){
try{
jbInit();
}catch(Exception e){
e.printStackTrace();
}
serverListen();//服务器开始监听
}
private void jbInit(){//初始化界面
panel=new Panel();
sPanel=new ScrollPane();
textArea=new TextArea("server information:\n");
button1=new Button("退出");
sPanel.add(textArea);
button1.addActionListener(new java.awt.event.ActionListener(){//退出按钮注册
public void actionPerformed(ActionEvent e){
button1_actionPerformed(e);
}
});
panel.add(button1);
this.addWindowListener(new ChatFrame_WindowAdapter(this));//注册到继承了窗口适配器的类
this.setSize(600,300);
this.setBackground(Color.GREEN);
this.setLayout(new BorderLayout());
this.add(sPanel,BorderLayout.CENTER);
this.add(panel,BorderLayout.SOUTH);
this.show();
}
private void button1_actionPerformed(ActionEvent e){
exit();
}
public void processMsg(String str){//
textArea.append(str);
}
private void serverListen(){
try{
serverSock=new ServerSocket(8080);
}catch(IOException e){
processMsg(e.toString());
processMsg("server failed!\n");
}
processMsg("server listening on port:"+DEFAULT_PORT);
clients=new java.util.Vector();
clientsInfor=new java.util.Vector();
chatAcceptThread=new Thread(this);//启动接受连接的线程
chatAcceptThread.start();
broadcastThread=new BroadcastThread(this);//广播线程
broadcastThread.start();
//还有一个回收无用连接thread 的线程
}
public void run(){//接受连接并记录线程信息
int i=0 ;
try{
while(true){
Socket clientSock=serverSock.accept();
CommunicateThread ct=new CommunicateThread(clientSock,this,index);//创建线程保持连接
clients.add(ct);//record Communicate Thread;
processMsg("\n");
i++;
index++;//version2
clientsInfor.add("Thread-"+i);
processMsg("Thread-"+i +"join in\n");
processMsg( "当前共有"+ i +"人在线");
}
}catch(IOException e){
processMsg(e.toString());
}
}
public void exit(){
broadcastThread.broadcast("Server exit!");
try{
serverSock.close();
}catch(IOException ioe){}
finally{
System.exit(0);
}
}
public static void main(String[] args){
ChatRoomServer chat=new ChatRoomServer();
}
}
class CommunicateThread extends Thread{//保持连接线程
protected Socket clientSock;
protected BufferedReader in=null;
protected PrintWriter out;
ChatRoomServer chatFrame;
boolean isTrue=true;//run()
java.util.Vector inforStack;
int index2;//
public CommunicateThread(Socket Sock,ChatRoomServer cFrame,int index){
clientSock=Sock;
chatFrame=cFrame;
index2=index;
inforStack=new java.util.Vector();
try{
in=new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
out=new PrintWriter(clientSock.getOutputStream());
}catch(IOException ei){
try{
clientSock.close();
}catch(IOException ei2){ }
chatFrame.processMsg(ei.toString());
return;
}
this.start();
}
public void run(){
String infor;
try{
while(isTrue){
infor=in.readLine();
if(infor.equals("Client exit!")){
writeInformation(infor);//把信息写到信息栈,以倍广播出去
stopRun();
}else if(infor!=null){
writeInformation(infor);
}//else break;
try{
Thread.sleep(100);//version2
}catch(InterruptedException ex){}
}
}catch(IOException e){ ;}
finally{
try{
in.close();
out.close();
clientSock.close();
chatFrame.clients.remove(index2);//在clients中清除本线程序
ChatRoomServer.index--;//
}catch(IOException ei){;}
}
}
public void writeInformation(String infor){//写信息栈
inforStack.add(infor);
}
private void stopRun(){//终止线程
isTrue=false;
}
public void sendInformation(String str){//发送信息
try{
out.println(str);
out.flush();
}catch(Exception e){;}
}
}
class BroadcastThread extends Thread{//广播线程
ChatRoomServer chatFrame2;
java.util.Vector chatClients;//连接线程信息
java.util.Vector msgStack;//信息栈
java.util.Vector clientMsg;//记录客户发送的信息
CommunicateThread comThread1;
CommunicateThread comThread2;
String string;//information in inforStack
String clientName;//client thread name
String broadcastInfor;//broadcast information=clientName+string;
public BroadcastThread(ChatRoomServer cFrame){
chatFrame2=cFrame;
chatClients=chatFrame2.clients;
clientMsg=chatFrame2.clientsInfor;
//this.start();
}
public void broadcast(String str){//广播
for(int k=0;k<chatClients.size();k++){//send to everyone分别调用每个连接线程,发送信息
comThread2=(CommunicateThread)chatClients.get(k);
comThread2.sendInformation(str);
}
}
public void run(){
try{
while(true){
for(int i=0;i<chatClients.size();i++){
comThread1=(CommunicateThread)chatClients.get(i);
msgStack=comThread1.inforStack;//得到每个连接的信息栈
clientName=(String)clientMsg.get(i);//客户名
//读取每个连接线程的信息栈并把信息发送出去
for(int j=0;j<msgStack.size();j++){
string=(String)msgStack.get(j);
broadcastInfor=clientName +"->"+string;
broadcast(broadcastInfor);
}
//clear the inforStack
msgStack.removeAllElements();//清除以发送的信息
}
try{
Thread.sleep(100);//version2
}catch(InterruptedException ex){}
}
}catch(Exception e){}
}
}
//处理窗口关闭事件的适配器
class ChatFrame_WindowAdapter extends java.awt.event.WindowAdapter{
ChatRoomServer chatFrame;
public ChatFrame_WindowAdapter(ChatRoomServer chatFrame){
this.chatFrame=chatFrame;
}
public void windowClosing(WindowEvent e){//exit program
chatFrame.exit();//reference to the method exit() in ChatRoomServer.
}
}
解决方案 »
- java求助
- JAVA报错?求解,急~~
- 要在C/S系统中实现报表格式的任意定制,请问应该使用什么报表啊?
- 偶想学习Java,就是英语不好,不知道影响大不大??
- 平滑直线图的算法
- 什么叫虚拟机呢?他就如何定义了,望大家给于解答,赠分!
- jdbc中多个连接的事务处理如何解决?我用的是sqlserver2000的jdbc驱程
- JavaMail , JMF , ... ,各位觉得最有用的Java库还有那些呢?
- 拜托,帮我看看出了什么问题!为什么总说:add(panel1)出错?
- JMenu 快捷键无效
- 求助:关于数据连接问题!好心人来帮帮我
- 在线等(急问) : 如何在我的程序中实现 服务器端向客户端返回 数据
public class Server {//主服务器类
public static void main(String args[]) throws IOException {
ServerSocket s = new ServerSocket(8080);//在8080端口创建套接口
System.out.println("Server start.." + s);
try {
while (true) {
Socket socket = s.accept();//无限监听客户的请求
System.out.println("Connectino accept:" + socket);
try {
new ServerThread(socket);//创建新线程
} catch (IOException e) {
socket.close();
}
}
} finally {
s.close();
}
}
}
客户端连接服务器发出请求
Socket socket = new Socket(InetAddress.getByName(server), serverport);//连务器
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println("request");
服务器端接受请求,发出回映
public ServerThread(Socket s) throws IOException {//线程构造函数
socket = s;//取得传递参数
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//创建输入流
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);//创建输出流
start();//启动线程
}public void run(){
while(true){
String str = in.readLine();//取得输入字符串
if ("request".equals(str)){
out.println("response");
}
}
}
以上是用数据流实现服务器与客户进行通信。也可以用数据报的形式进行通信,但是不太可靠。