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

多線程對多個客戶端的監聽

2022-06-13   來源: Java高級技術 

  這是一個比較簡單的例子來說明socket編程服務器端使用了多線程來監聽客戶端

  服務器端的代碼

  package SocketTest;

  import javaio*;

  import *;

  import javautil*;

  class SocketServer{

  public SocketServer(){

  Socket incoming;

  ServerSocket so;

  try{

  so= new ServerSocket();

  Systemoutprintln(等待客戶端連接);

  while(true){

  try{

  incoming = soaccept( );

  Systemoutprintln(已連接客戶端);

  GetInfo gi=new GetInfo(incoming);//調用線程

  } catch (IOException e){

  eprintStackTrace();

  }

  }

  }catch (IOException e){

  eprintStackTrace();

  }

  }

  public static void main(String[] args){

  new SocketServer();

  }

  private static class GetInfo implements Runnable{   //線程類

  private Socket incoming;

  private String s=null;

  private BufferedReader b;

  Thread t;

  public GetInfo(Socket incoming){

  try{

  thisincoming=incoming;

  b=new BufferedReader(new InputStreamReader(incominggetInputStream()));

  t=new Thread(this);

  tstart();

  }catch(IOException e){

  eprintStackTrace();

  }

  }

  public void run(){

  try{

  while (true){

  s=breadLine();

  Systemoutprintln(s);

  if(sequals(end)){

  break;

  }

  }

  }catch(IOException e){

  eprintStackTrace();

  }

  }

  }

  }

  客戶端的代碼

  package SocketTest;

  import javaio*;

  import *;

  import javautil*;

  public class SocketClient{

  public static void main(String[] args){

  try{

  Socket so = new Socket(localhost );

  Systemoutprintln(連接服務器);

  BufferedReader b=new BufferedReader(new InputStreamReader(Systemin));

  OutputStream outStream = sogetOutputStream();

  PrintWriter out = new PrintWriter(outStream);

  String s=null;

  while (true){

  s=breadLine();

  outprintln(Client:+s);

  outflush();

  if(sequals(end)){

  break;

  }

  }

  }catch (IOException e){

  eprintStackTrace();

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27636.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.