JAVA制作聊天室(服务器端和客户端)

JAVA制作聊天室(客户端)

/*客户端连接(myClient.java)*/
package itbaby.jchat;
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;

public class myClient extends Thread
{
  static Socket server;
  TextArea jTextArea1;
  List List1;
  PrintWriter out;
  OutputStream outs;
  String sUserName ;
  String sIPAddr;

  public myClient(TextArea _jTextArea1,List _List1,String _sUserName,String sIP)
  {
    this.jTextArea1 = _jTextArea1;
    this.List1 = _List1;
    this.sUserName = _sUserName;
    this.sIPAddr = sIP;
  }

  public void SendMessage(String sMessage)//发送公聊消息
  {
    out.println("["+this.sUserName + "]:" + sMessage);
    out.flush();
  }

  public void SendMessagePrivate(String privateUser,String sMessage)//发送私聊消息
  {
    out.println("sendto:"+privateUser+"["+this.sUserName + "]:"+ sMessage);
    out.flush();
  }


  public void SendWelcome()//发送欢迎消息给服务器,由服务器广泊消息
  {
    out.println("cmd:welcome"+sUserName);
    out.flush();
  }


  public void run()
  {
    try
    {
      myClient.server = new Socket(this.sIPAddr, 2005);
      outs = server.getOutputStream();
      out = new PrintWriter(outs);


      myClientThread myCT = new myClientThread(this.jTextArea1,this.List1);
      myCT.start();

      this.SendWelcome();

      //BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
      /*while (true) //控制台方式的测试客户端
       {
        String str = wt.readLine();
        out.println(str);
        out.flush();
        if (str.equals("end"))
          break;
      }
      out.close();
      server.close();*/
    }
    catch(Exception ex)
    {
      String exmsg = ex.getMessage();
      System.out.println(exmsg);
    }

  }

  public static void main(String[] args)throws Exception
    {

      }

}

 

 

/*客户端的线程处理程序(myClientThread.java)*/
package itbaby.jchat;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.*;
import java.lang.*;
import java.awt.*;

public class myClientThread extends Thread
{
  TextArea jTextArea1;
  java.awt.List List1;
  public myClientThread(TextArea _jTextArea1,java.awt.List _List1)
  {
    this.jTextArea1 = _jTextArea1;
    this.List1 = _List1;
  }

  public void run()
  {

    while(true)
    {
      try
      {
        BufferedReader in = new BufferedReader(new InputStreamReader(myClient.server.getInputStream()));
        String sMsg = in.readLine();
        if(sMsg.indexOf("cmd:userlist")!=-1)
        {
          //用户列表
          sMsg = sMsg.substring(12,sMsg.length());
          this.List1.removeAll();
          String sUsr = "";
          for(int i=0;i<sMsg.length();i++)
          {

            if(sMsg.charAt(i)=='|') //用户名称都使用|分隔
            {
              this.List1.add(sUsr);
              sUsr = "";
            }
            else
              sUsr = sUsr + String.valueOf(sMsg.charAt(i));
          }

        }
        else
          this.jTextArea1.append(sMsg+'/n');//聊天信息
      }
      catch(Exception ex)
      {
        String exmsg = ex.getMessage();
        System.out.println(exmsg);
      }
    }
  }

}

 

/*简单的描述客户端GUI的程序,GUI省去*/

 

//在系统加载后,点击登录按钮后,执行初始化客户端连接
myClient mClient; //全局类

 

//TextArea1  消息显示
//List1      用户列表
//jTextField1 消息输入区
//jTextField4 文件传输路径名
mClient = new myClient(TextArea1,List1,jTextField1.getText(),jTextField4.getText());
mClient.start();

//有一个发送按钮,点击时,执行如下代码
if(jTextField2.getText().length()==0)return;
    if(checkbox1.getState())//私聊信息
    {
      if (jLabel4.getText().length() != 0)
        mClient.SendMessagePrivate(jLabel4.getText(),
                                   this.jTextField2.getText());
    }
    else//公聊
      mClient.SendMessage(jTextField2.getText());

    jTextField2.setText("");


  <script language="javascript" type="text/javascript">document.title="JAVA制作聊天室(服务器) - "+document.title</script>

JAVA制作聊天室(服务器)

 

/*服务器主程序(myServer.java)*/
package itbaby.jchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;


public class myServer
{
  static ArrayList clients = new ArrayList();
  static ArrayList onlineUser = new ArrayList();
  static ArrayList onlineIP = new ArrayList();
  public myServer()
  {
  }

  public static void cleanupListenList()
    {
 /*
 检查当前在线的用户数,在线程中被调用
 */
        for (int i = clients.size()-1; i > -1; i--){
            myServerThread client = (myServerThread) clients.get(i);
            if ( ! client.isAlive() )
            {
                String sBye = "再见 " + (String)onlineUser.get(i);
                client.kill();
                clients.remove(i); //移除一个断开的线程
                onlineUser.remove(i);
                onlineIP.remove(i);
                myServerThread.SendToAllUser();//更新在线用户
                myServerThread.SendToAll(sBye);//显示再见消息
                System.out.println("连接断开...");
            }
        }


    }

    public static  void main( String argv[] ) throws IOException
    {
      ServerSocket listener = new ServerSocket(2005);
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      PrintWriter out = new PrintWriter(System.out,true);

      System.out.println("Running...");
      System.out.println("Port:2005");
      myUserRefresh myURef = new myUserRefresh();
      myURef.start();

      while (true)
      {
        Socket client = listener.accept();//等待客户端连接
        myServerThread myClientThread = new myServerThread(client); //有连接进入,开始执行一个线程
        myClientThread.start();
        myServer.clients.add(myClientThread);    //记录有效的线程
        myServer.cleanupListenList();
      }

    }

}

 

 


/*聊天的线程处理程序(myServerThread.java)*/
package itbaby.jchat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;


public class myServerThread extends Thread
{
  private Socket Client;
  boolean stillRunning = true;
  public PrintWriter pout;

  public myServerThread(Socket _client)
  {
    Client = _client;
  }

  public void kill()
  {
    stillRunning = false;
  }

  public static void SendToAll(String sMsg)//公聊
  {
    for(int i=0;i<myServer.clients.size();i++)
    {
      myServerThread th = (myServerThread)myServer.clients.get(i);
      th.pout.println(sMsg + " ("+ th.getTime() +")");
    }
  }

  public void SendToPrivate(String sPrivateUser,String sMsg)//私聊
  {
    for(int i=0;i<myServer.clients.size();i++)
    {
      String sIP = (String)myServer.onlineIP.get(i);
      String sUs = (String)myServer.onlineUser.get(i);
      String sUser = sUs + "("+sIP+")";
      if(sPrivateUser.trim().equals(sUser.trim()))
      {
        myServerThread th = (myServerThread)myServer.clients.get(i);
        th.pout.println("PrivateMessage:" +sMsg + " ("+ th.getTime() +")");
        break;
      }
    }

  }


  public static void SendToAllUser()//所有在线用户列表数据
  {
    String sUser = "";
    int iCount = myServer.clients.size();
    for(int i=0;i<iCount;i++)
    {
      String sIP = (String)myServer.onlineIP.get(i);
      String sUs = (String)myServer.onlineUser.get(i);
      sUser = sUser + sUs + "(" + sIP + ")|";
    }

    for(int i=0;i<iCount;i++)
    {
      myServerThread th = (myServerThread)myServer.clients.get(i);
      th.pout.println("cmd:userlist"+sUser);
    }

  }

 

  public String getTime()
  {
    //String sTime = "";
    java.text.DateFormat format1 = new java.text.SimpleDateFormat("hh:mm:ss");
    java.util.Date currentTime_2 = new java.util.Date();
    String sTime=format1.format(currentTime_2);

    return sTime;
  }


  public String getClientIP()
  {
    return (Client.getInetAddress()).toString();
  }

  public void run()
  {
    try
    {
      //(Client.getInetAddress()).toString() );
      InputStream in =  Client.getInputStream();
      InputStreamReader textIn = new InputStreamReader(in);
      BufferedReader textLineIn = new BufferedReader(textIn);
      OutputStream out = Client.getOutputStream();
      pout = new PrintWriter(out,true);


      while(stillRunning)
      {

          String someText = textLineIn.readLine();
          if (someText.length() != 0)
          {
            if (someText.indexOf("cmd:welcome") != -1)
     { //欢迎消息
              String sUser = someText.substring(11, someText.length());
              this.SendToAll("Welcome " + sUser + " from " + this.getClientIP());

              myServer.onlineIP.add(this.getClientIP());
              myServer.onlineUser.add(sUser);

              //发送用户列表数据
              myServerThread.SendToAllUser();
            }
            else if (someText.indexOf("sendto:") != -1)
            { //私聊
              String sUser = someText.substring(7, someText.indexOf(")") + 1);
              someText = someText.substring(someText.indexOf(")") + 1,
                                            someText.length());
              pout.println("PrivateMessage:" + someText + " (" + this.getTime() + ")"); //自己发送的,自己回显聊天语句
              this.SendToPrivate(sUser, someText); //接受人,显示聊天语句
            }
            else myServerThread.SendToAll(someText); //发送公共聊天消息

          }
        }

    }
    catch (IOException e)
    {
      System.out.println( "I/O Error They probably left " + e);
    }

  }

}

 

 


/*刷新用户*/
package itbaby.jchat;


public class myUserRefresh extends Thread
{
  public myUserRefresh() {
  }

  public void run()
  {
    while(true)
    {
      myServer.cleanupListenList();
    }
  }
}

 

发布了3 篇原创文章 · 获赞 1 · 访问量 46万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览