欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java Socket通信之聊天室功能

程序员文章站 2024-02-20 12:50:46
本文实例为大家分享了java socket聊天室功能的具体代码,供大家参考,具体内容如下 client.java import java.io.*; imp...

本文实例为大家分享了java socket聊天室功能的具体代码,供大家参考,具体内容如下

client.java

import java.io.*; 
import java.net.*; 
import java.util.*; 
 
public class client { 
 public int port = 8083; 
 socket socket = null; 
 
 public static void main(string[] args) { 
  new client(); //开始执行 
 } 
 
 public client() { 
 
  try { 
   socket = new socket("127.0.0.1", port); 
   new cthread().start(); 
 
   bufferedreader br = new bufferedreader(new inputstreamreader(socket.getinputstream())); 
   string msg1; 
   while ((msg1 = br.readline()) != null) { 
    system.out.println(msg1); 
   } 
  } catch (exception e) { 
  } 
 } 
 
 class cthread extends thread { 
 
  public void run() { 
   try { 
 
    bufferedreader re = new bufferedreader(new inputstreamreader(system.in)); 
    printwriter pw = new printwriter(socket.getoutputstream(), true); 
    string msg2; 
 
    while (true) { 
 
     msg2 = re.readline(); 
     pw.println(msg2); 
    } 
   } catch (exception e) { 
    e.printstacktrace(); 
   } 
 
  } 
 } 
 
} 

server.java

import java.net.*; 
import java.io.*; 
import java.util.*; 
 
public class server { 
  int port; 
  list<socket> clients; 
  serversocket server; 
  public server() { 
    try { 
      port = 8083; 
      clients = new arraylist<socket>(); 
      server = new serversocket(port); 
      system.out.println("服务器已启动"); 
      int co=1; 
      while (true) { 
        socket socket = server.accept(); 
        clients.add(socket); 
        mythread mythread = new mythread(socket,co); 
        co++; 
        mythread.start(); 
      } 
 
    } catch (exception ex) { 
      system.out.println("vv"); 
    } 
  } 
 
  public static void main(string[] args) { 
    new server(); 
  } 
 
  class mythread extends thread { 
    socket ssocket; 
    private int count; 
    private bufferedreader br; 
    private printwriter pw; 
    public string msg; 
 
    public mythread(socket s,int c) { 
      ssocket = s; 
      count=c; 
    } 
 
    public void run() { 
 
      try { 
        br = new bufferedreader(new inputstreamreader(ssocket.getinputstream())); 
         
        msg = "欢迎【" +"client "+count + "】进入聊天室!当前聊天室有【" + clients.size() + "】人"; 
 
        sendmsg(); 
 
        while ((msg = br.readline()) != null) { 
           
          msg = "【" +"client "+count + "】说:" + msg; 
          sendmsg(); 
 
        } 
      } catch (exception ex) { 
      } 
    } 
    public void sendmsg() { 
      try { 
        system.out.println(msg); 
 
        for (int i = clients.size() - 1; i >= 0; i--) { 
          pw = new printwriter(clients.get(i).getoutputstream(), true); 
          pw.println(msg); 
          pw.flush(); 
        } 
      } catch (exception ex) { 
      } 
    } 
  } 
 
} 

运行结果:

Java Socket通信之聊天室功能

Java Socket通信之聊天室功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。