Java下基于Socket的多线程聊天室

刚刚完成了一个Java下基于Socket的多线程聊天室,与大家分享一下:

 

介绍一下我本地实现的软件详细信息以供参考:

 
操作系统:Microsoft Windows XP Professional SP3
Java JDK:JDK1.6.0_02
Eclipse :Eclipse-SDK-3.2-WIN32

 

服务器端:

import java.io.*;
import java.net.*;
import java.util.*;

public class ServerSocketSample extends ServerSocket
{
 private static ArrayList Threader = new ArrayList();
 private static LinkedList Message_Array = new LinkedList();
 private static boolean isClear = true;
 private static int Thread_Counter = 0;
 protected static final int SERVER_PORT = 1025;

 public ServerSocketSample() throws IOException
 { 
  super(SERVER_PORT);  //parent class Construct Methods(ServerSocket) 
 }

 //create socket listen link from client
 public void initServer() throws IOException
 {
  System.out.println("Listening"); 

  //start send
  new MessBroadcast();

  try
  {
   while (true)
   {
    Socket socket = accept();
    new CreateServerThread(socket);
   }
  }
  finally
  {
   close();
  }
 }

 public static void main(String[] args) throws IOException,InterruptedException
 {
  System.out.println("Begin Listen");
  ServerSocketSample server = new ServerSocketSample();
  server.initServer();
 }

 //start send
 //create thread listen messs and send mess to all client
 class MessBroadcast extends Thread
 {
  public MessBroadcast()
  {
   System.out.println("Begin Broadcast");
   start();
  }

  public void run()
  {   
   System.out.println("Broadcasting");
   while (true)
   {    
    if (!isClear)
    {
     //read current new mess
     String tmp = (String)Message_Array.getFirst();
     
     //read link client
     System.out.println(Threader.size());
     
     //send mess to all client
     for (int i = 0; i < Threader.size(); i++)
     {
      CreateServerThread client = (CreateServerThread)Threader.get(i);
      client.sendMessage(tmp);
     }
     Message_Array.removeFirst();
     isClear = Message_Array.size() > 0 ? false : true;
    }
    else
    {
     try
     {
      Thread.sleep(1000);
     }
     catch(Exception ex)
     {}
    }
   }
  }
 }

 //start listening
 //make listener to listen message and link from client
 class CreateServerThread extends Thread
 {
  private Socket client;
  private BufferedReader in;
  private PrintWriter out;
  private String Username;

  public CreateServerThread(Socket s) throws IOException
  {
   System.out.println("Get Connection");

   client = s;
   in = new BufferedReader(new InputStreamReader(client.getInputStream()));
   out = new PrintWriter(client.getOutputStream(), true);
   start();
  }

  public void run()
  {
   try
   { 
    int flag = 0;
    Thread_Counter++;
    out.println("--- Welcome! Please Input your nickname: ---");
    String line = in.readLine();
    
    //listen new user link
    while (!line.equals("end"))
    {
     if (line.equals("l"))
     {
      System.out.println("+ Username +!");
      line = in.readLine();
      continue;
     }
     if (flag++ == 0)
     {      
      Username = line;

      Threader.add(this);
      pushMessage("[ " + Username + " come in ]");
     }
     else
     {
      pushMessage("[" + Username + "]:" + line); 
     }

     line = in.readLine();
    }
    out.println("--- See you, bye! ---");
    client.close();
   }
   catch (IOException e)
   {}
   finally
   {
    try
    {
     client.close();  
    }
    catch(Exception error)
    {}
    
    Thread_Counter--;
    Threader.remove(this);
    //user left
    pushMessage("[< " + Username + " left>]");
   }
  }
  
  //send mess to client
  public void sendMessage(String msg)
  {
   out.println(msg);
  }

  //add information to the Message Queue
  private void pushMessage(String msg)
  {
   Message_Array.addLast(msg);
   isClear = false;
  }
 }
}

 

客户端:

import java.io.*;
import java.net.*;

public class ClientSocketSample
{
 Socket socket;
 BufferedReader in;
 PrintWriter out;
 ListenThread linstener;

 public ClientSocketSample() 
 {
  try
  {
   System.out.println("Begin Connection");
   socket = new Socket("127.0.0.1", 1025);   
  }
  catch (IOException e)
  {}
 }

 public void ClientRun() throws IOException
 {
  System.out.println("Connectioning");
  in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  out = new PrintWriter(socket.getOutputStream());

  //console input
  BufferedReader clientmess = new BufferedReader(new InputStreamReader(System.in));

  //read server welcome message()
  System.out.println(in.readLine());

  //read nickname from console
  String mess = clientmess.readLine();

  //send nickname to server   
  out.println(mess);
  out.flush();

  //make listener to listen message from server
  linstener = new ListenThread(socket);
  linstener.start();

  //listen stdin input message and send to server
  while(true)
  {   
   mess = clientmess.readLine();    
   out.println(mess);
   out.flush();

   //if input is end ,break listen
   if(mess.equals("end"))
   {
    break;
   }
  }   

  socket.close();
  System.out.println("Client Close");
 }

 public static void main(String[] args) throws Exception
 {
  ClientSocketSample Client = new ClientSocketSample();
  Client.ClientRun();
 }

 //make listener to listen message from server
 class ListenThread extends Thread
 {
  private Socket socket_con;

  public ListenThread(Socket s) throws IOException
  {   
   socket_con = s;
   in = new BufferedReader(new InputStreamReader(socket_con.getInputStream()));
   out = new PrintWriter(socket_con.getOutputStream(), true);
  }

  public void run()
  {
   try
   { 
    String line;
    while (!socket_con.isClosed())
    {
     line = in.readLine();
     System.out.println(line);
    }
   }
   catch (IOException e)
   {}
  }
 }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值