开发者社区> 问答> 正文

java如何使用Socket实现多线程多人聊天

java如何使用Socket实现多线程多人聊天,提供源码最好了。希望说详细一点。

展开
收起
蛮大人123 2016-03-12 16:35:17 2771 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    简单的聊天室:

    server:
    
    import  java.net.*; 
    import  java.io.*; 
    import  java.util.*; 
    
    public  class  ServerSocketDemo   
    {
    
        public  static  void  main(String[]  args) 
        { 
            ArrayList list = new ArrayList();
            ServerSocket  ss = null;
    
            try {
                ss =new  ServerSocket(8189); 
    
                while(true) 
                { 
                    Socket  s=ss.accept(); 
                    list.add(s); 
                    new  ReverseDemo(s,list); 
                }
            }catch( Exception ex ) {
            }
            try {
                ss.close();
            }catch( Exception ex ) {
            } 
        }
    }
    
    import  java.net.*; 
    import  java.io.*; 
    import  java.util.*; 
    
    public class  ReverseDemo  extends  Thread 
    { 
        BufferedReader  in=null; 
        PrintWriter  out=null; 
        String  str="abc"; 
        ArrayList  list; 
        Socket  s; 
    
        public  ReverseDemo(Socket  s,ArrayList  list) 
        { 
            this.list=list; 
            this.s=s; 
            this.start(); 
        }
        public  void  run() 
        { 
    
            try 
            { 
                InputStream inStream = s.getInputStream();
                OutputStream outStream = s.getOutputStream();
    
                PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);
                System.out.println(s.getInetAddress().getHostAddress()+"  connected-------");
                out.println("连接成功!");
    
                byte[] buf = new byte[1024];
    
                while(true) 
                {
                    int bytes_read = inStream.read( buf );
                    if( bytes_read < 0 ) {
                        break;
                    } else {
                        broadcast( buf, 0, bytes_read );
                    }       
                } 
              } 
              catch  (Exception  ex) 
              { 
                  ex.printStackTrace(); 
              }
              finally {
                  list.remove( s );
              } 
        }
    
    
        void broadcast( byte[] b, int offset, int length ) {
            for( int i = 0, n = list.size(); i < n; i++ ) {
                Socket sock = (Socket) list.get( i );
                if( sock != s ) {
                    try {
                        sock.getOutputStream().write( b, offset, length );
                        sock.getOutputStream().flush();
                    }catch( Exception ex ) {
                    }
                }
            }
        }
    } 

    client:

    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    /**
      This program makes a socket connection to the atomic clock
      in Boulder, Colorado, and prints the time that the
      server sends.
    */
    public class SocketTest
    {
        private Socket sock_;
        private byte[] name_; 
    
        public SocketTest( String host, int port, byte[] name ) throws Exception {
            name_ = name;
            sock_ = new Socket( host, port );
            Thread th = new Thread( createMsgRecvRunnable() );
            th.start();
            byte[] b = new byte[ 1024 ];
    
            int bytes_read = readMsg( b );
            while( bytes_read > 0 ) {
                sendMsg( b, 0, bytes_read );
                bytes_read = readMsg( b );
            }
        }
    
        private Runnable createMsgRecvRunnable() {
            return new Runnable() {
                public void run() {
                    try {
                        InputStream in = sock_.getInputStream();
                        byte[] buf = new byte[1024];
    
                        while( true ) {
                            int bytes_read = in.read( buf );
                            if( bytes_read < 0 ) {
                                break;
                            } else {
                                System.out.write( buf, 0, bytes_read );
                            }
                        }
                    }catch( Exception ex ) {
                    }
                }
            };
        }
    
        private int readMsg( byte[] b ) throws Exception {
            return System.in.read( b );
        }
    
        private void sendMsg( byte[] msg, int offset, int length ) throws Exception {
            sock_.getOutputStream().write( name_ );
            sock_.getOutputStream().write( msg, offset, length );
            sock_.getOutputStream().flush();
        }
    
        public static void main( String[] args ) {
            try {
                String name = null;
    
                if( args.length > 0 ) {
                    name = args[0] + ":";
                } else {
                    name = "unknown:";
                }
                SocketTest test = new SocketTest( "localhost", 8189, name.getBytes() );
            }catch( Exception ex ) {
                ex.printStackTrace();
            }
        }
    
    } 
    2019-07-17 19:01:11
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载