程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> socket-java如何使用Socket實現多線程多人聊天

socket-java如何使用Socket實現多線程多人聊天

編輯:編程綜合問答
java如何使用Socket實現多線程多人聊天

java如何使用Socket實現多線程多人聊天,提供源碼最好了。希望說詳細一點。

最佳回答:


簡單的聊天室:

 ==========================================================================================
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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved