首页 > 技术文章 > 服务器端启动soket多线程

java-php 2015-08-19 23:34 原文

 

方法一:

Socket socket=null

try{

  ServerSocket serversocket=nwe ServerSocket(8080)

  while(true){

    socket=serversocket.apccet();

    new ServerThread(socket).start();

  }

}catch(IOException e){

  e.printStackTrace()

}

 

方法二:

public  class ServerThread extends Thread{

  private Socket socket;

  public ServerSocket(socket){

    this.socket=socket;

  }

  public void run(){

      //复写run方法

    InputStream is=null;

    OutputStream os=null;

    String ip=socket.getLocalAddress().getHostAddress();

    String port=socket.getPort();

    try{

      while(true){

        in=socket.getInputStream();

        byte[] buffer=new byte[1024];

        int index=in.read(buffer);

        String receive=new String(buffer,0,index);

        System.out.println ("接受到服务器的内容是"+receive);

        if(recive=="exit") break;

        out=sokect.getOutputStream();

        String mes="word";

        out.write(mes.getBytes());

        System.out.println ("向服务器发送的内容:"+receive);

      }

      in.close();

      out.close();

      socket.close();

    }catch(IOException){

      e.printStackTrace();

    }

  }

}

推荐阅读