正文

服务器端charroomserver2006-06-07 10:30:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/sword2008/15515.html

分享到:

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

 

阅读(683) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册