ServerPoint.java
资源名称:chat.rar [点击查看]
上传用户:qaz007_wsx
上传日期:2022-06-21
资源大小:3k
文件大小:4k
源码类别:
ICQ/即时通讯
开发平台:
Java
- //ServerPoint.java
- import java.net.*;
- import java.io.*;
- public class ServerPoint extends Thread{
- static int SERVERPORT=8088; //端口
- private Socket client;
- public static int i=0;
- public static String[] vct=new String[10];
- public ServerPoint(){} //构造方法
- public void run(){
- ClientThread.log("服务器端程序启动...");
- try{
- ServerSocket server=new ServerSocket(SERVERPORT);
- while(true){
- client=server.accept();
- ClientThread ct=new ClientThread(client);
- ct.start();
- }
- }catch(Exception e){
- e.printStackTrace();
- ClientThread.log("服务器端程序关闭。。。");
- System.exit(0);
- }
- }
- public static void main(String[] args){
- ServerPoint sp=new ServerPoint();
- sp.start();
- } //主函数
- public static synchronized void message(String msg){
- vct[i]=msg;
- i=(i+1)%10;
- vct[i]="*";
- }
- }
- class ClientThread extends Thread{
- private static int ii=0;
- private Socket s;
- String msg=null;
- ServerSocket serverSocket=null;
- Socket socket=null;
- BufferedReader cin=null;
- PrintWriter cout=null;
- public ClientThread(Socket s){
- this.s=s;
- }
- public void run(){
- try{
- cin=new BufferedReader(
- new InputStreamReader(s.getInputStream()));
- cout=new PrintWriter(s.getOutputStream());
- SendToAll sta=new SendToAll();
- sta.start();
- msg=cin.readLine();
- ii++;
- System.out.println("some connect us!聊天室里总共有"+ii+"个人"); //连接登录上的客户数
- while(!msg.equals("exit")){
- ServerPoint.message(msg);
- msg=cin.readLine();
- }
- if(msg.equals("exit"))
- { --ii;
- System.out.print("someone exitn聊天室里总共有"+ii+"个人");
- //有用户退出后的聊天人数
- cin.close();
- cout.close();
- s.close();
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- static void log(String strInfo){
- System.out.println(strInfo);
- }
- class SendToAll extends Thread{
- private int j=-1;
- public void run(){
- while(true)
- {
- try{
- sleep(500);
- if(j==-1){
- if(!ServerPoint.vct[0].equals("*")){
- cout.println(ServerPoint.vct[0]);
- cout.flush();
- j=1;
- }
- else {
- cout.println(ServerPoint.vct[1]);
- cout.flush();
- j=2;
- }
- }
- while(!ServerPoint.vct[j].equals("*"))
- {
- cout.println(ServerPoint.vct[j]);
- cout.flush();
- j=(j+1)%10;
- }
- }catch(Exception e){}
- }
- }
- }
- }