熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java進行並發多連接socket編程

2022-06-13   來源: Java核心技術 

  Java多個客戶端同時連接服務端在現實生活中用得比較多同時執行多項任務第一想到的當然是多線程了下面用多線程來實現並發多連接

import javanet*;
import javaio*;

public class ThreadServer extends Thread
{
    private Socket client;

    public ThreadServer(Socket c)
    {
        thisclient=c;
    }

    public void run()
    {
        try
        {
            BufferedReader in=new BufferedReader(new InputStreamReader(clientgetInputStream()));
            PrintWriter out=new PrintWriter(clientgetOutputStream());
            //Mutil User but cant parallel

            while (true)
            {
                String str=inreadLine();
                Systemoutprintln(str);
                outprintln(has receive);
                outflush();
                if (strequals(end))
                    break;
            }
            clientclose();
        }
        catch (IOException ex)
        {
        }
        finally
        {

        }
    }
    public static void main(String[] args)throws IOException
    {
        ServerSocket server=new ServerSocket();
        while (true)
        {
            //transfer location change Single User or Multi User

            ThreadServer mu=new ThreadServer(serveraccept());
            mustart();
        }
    }
}


From:http://tw.wingwit.com/Article/program/Java/hx/201311/27248.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.