import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class charroomserver {
//----------------------------------------------------------****************定义变量
//JFrame
JFrame charFrame;
JTextArea charText;
JTextField charField2;
JButton charButton2;
ScrollPane sPanel;
//JPanel
JPanel jPanel1,jPanel2;
//端口号and net
public final static int DEFAULT_PORT=6666;//默认端口号
ServerSocket serverSock;
Socket clientSock;
//Thread
//Thread chatAcceptThread;//启动接受连接的线程
ChatAcceptThread chatAcceptThread;
//_________________________________________________________________________________
//------------------------------------------------------------***************方法
//服务端图形
void gUi(){
//new
charFrame=new JFrame("聊天室服务端");
jPanel2=new JPanel();
charButton2=new JButton("退出");
charText=new JTextArea(20,20);
sPanel=new ScrollPane();
charField2=new JTextField(20);
Container chartain=charFrame.getContentPane();
//add
sPanel.add(charText);charText.setLineWrap(true);
jPanel2.add(charButton2);
jPanel2.add(charField2);
// chartain.add(jPanel1,BorderLayout.NORTH);
chartain.add(sPanel,BorderLayout.CENTER);
chartain.add(jPanel2,BorderLayout.SOUTH);
charFrame.setBounds(200,200,500,400);
charFrame.setVisible(true);
charFrame.pack();
charFrame.show();
//-------------------------------------------------------***************监听
//_________________________________________________________________________________
}
//监听
void serverListen(){
try{
serverSock=new ServerSocket(DEFAULT_PORT);
while(true){
clientSock=serverSock.accept();
chatAcceptThread=new ChatAcceptThread(clientSock);//启动接受连接的线程
chatAcceptThread.start();
}
}catch(IOException e){
}
}
//_________________________________________________________________________________
public charroomserver(){
gUi();
serverListen();//服务器开始监听
}
//----------------------------------------------------------************内部类
//线程,多用户连接
class ChatAcceptThread extends Thread{
Socket clientSock2;
public ChatAcceptThread(Socket upSock){
clientSock2=upSock;
}
//run
public void run(){
try{
BufferedReader in=new BufferedReader(new InputStreamReader(clientSock2.getInputStream()));
PrintWriter out=new PrintWriter(clientSock2.getOutputStream());
while(true){
String str=in.readLine();
// System.out.println(str);
charText.append(str);
out.println(str);
out.flush();
if(str.equals("end"))
break;
}
}
catch(Exception e){
}
}
}
//______________________________________________________________________________
public static void main(String args[]){
new charroomserver();
}
}
评论