lozone11
lozone11
2015-05-09 07:24
采纳率: 100%
浏览 5.8k
已采纳

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

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • liuyuxuan2388
    LemonSmile_ 2015-05-10 02:11
    已采纳

    简单的聊天室:

     ==========================================================================================
    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:
    
    
    /**
      @version 1.20 2004-08-03
      @author Cay Horstmann
    */
    
    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();
            }
        }
    
    } 
    

    多线程参考:
    Java Socket网络编程--聊天室的实现(多线程实现无需等待对方响应版本):http://wenku.baidu.com/link?url=LUqWTEcoIuO7wEzby14517TqNaDqOmKUEXrvGOegWKIa2Oq5tscyGkiRa0jkGPxxuGryTf4yhhvfoc2S-w6tsKJNoPDccI83gsfqYCLeokG

    点赞 评论
  • sfdff33
    tech555 2015-05-09 07:26
    点赞 评论
  • miss2671228
    miss2671228 2015-05-09 08:20

    源码比较长,把你邮箱留下下班后发给你。

    点赞 评论
  • rogeracer
    路边摆摊的 2015-05-09 10:12

    如果只是纯技术研究,可以研究一下 openfire 解决方案,是一款 移动IM解决方案,不过思路差不多的

    点赞 评论
  • QUAN19940604
    独执一叶 2015-05-09 10:42

    做一个服务器端,一个客户端,服务器负责转发就行了,具体代码留邮箱。

    点赞 评论

相关推荐