溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java中的多線程回顯服務(wù)器怎么利用Socket實(shí)現(xiàn)

發(fā)布時(shí)間:2020-12-02 17:28:25 來源:億速云 閱讀:146 作者:Leah 欄目:編程語言

Java中的多線程回顯服務(wù)器怎么利用Socket實(shí)現(xiàn)?相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

具體如下:

需要兩個(gè)類,一個(gè)是EchoServer,代表服務(wù)器。另外一個(gè)是EchoServerClient,代表客戶端。代碼如下:

package interview;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
  public static void main(String []args) throws IOException{
    ServerSocket server = new ServerSocket(6789);
    while(true){
      Socket client = server.accept();
      ClientHandler handler = new ClientHandler(client);
      new Thread(handler).start();
    }
  }
  public static class ClientHandler implements Runnable{
    private Socket client;
    @Override
    public void run() {
      InputStreamReader isr = null;
      try {
        isr = new InputStreamReader(client.getInputStream());
        BufferedReader br = new BufferedReader(isr);
        PrintWriter pw = new PrintWriter(client.getOutputStream());
        String msg = br.readLine();
        System.out.println("收到" + client.getInetAddress() + "發(fā)送的" + msg);
        pw.println("收到了你發(fā)的" + msg);
        pw.flush();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    public ClientHandler(Socket client){
      this.client = client;
    }
  }
}

下面是客戶端代碼:

package interview;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class EchoServerClient {
  public static void main(String []args) throws UnknownHostException, IOException{
    Socket client = new Socket("127.0.0.1", 6789);
    Scanner sc = new Scanner(System.in);
    System.out.print("請輸入要發(fā)送的內(nèi)容:");
    String msg = sc.nextLine();
    sc.close();
    PrintWriter pw = new PrintWriter(client.getOutputStream());
    pw.println(msg);
    pw.flush();
    InputStreamReader isr = new InputStreamReader(client.getInputStream());
    BufferedReader br = new BufferedReader(isr);
    System.out.println("服務(wù)器返回:" + br.readLine());
    client.close();
  }
}

NIO多路復(fù)用套接字方法如下:

package interview;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;
public class EchoServerNIO {
  private static ServerSocketChannel serverChannel = null;
  private static Selector selector = null;// 多路復(fù)用選擇器
  private static ByteBuffer buffer = null;  // 緩沖區(qū)
  public static void main(String []args) throws IOException{
    init();
    listen();
  }
  static void init() throws IOException{
    serverChannel = ServerSocketChannel.open();
    buffer = ByteBuffer.allocate(1024);
    serverChannel.socket().bind(new InetSocketAddress(6789));
    serverChannel.configureBlocking(false);
    selector = Selector.open();
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
  }
  static void listen() throws IOException{
    while(true){
      if(selector.select(5000) != 0){
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while(it.hasNext()){
          SelectionKey key = it.next();
          it.remove();
          handleKey(key);
        }
      }
    }
  }
  static void handleKey(SelectionKey key) throws IOException{
    SocketChannel channel = null;
    if(key.isAcceptable()){
      ServerSocketChannel serverChannel = (ServerSocketChannel)key.channel();
      channel = serverChannel.accept();
      channel.configureBlocking(false);
      channel.register(selector, SelectionKey.OP_READ);
    }else if(key.isReadable()){
      channel = (SocketChannel)key.channel();
      buffer.clear();
      if(channel.read(buffer) > 0){
        buffer.flip();
        CharBuffer charBuffer = CharsetHelper.decode(buffer);
        String msg = charBuffer.toString();
        System.out.println("收到" + channel.getRemoteAddress() + "的消息:" + msg);
        channel.write(CharsetHelper.encode(CharBuffer.wrap("received your msg:" + msg)));
      }
    }
  }
  public static class CharsetHelper{
    private static final String UTF_8 = "UTF-8";
    private static CharsetEncoder encoder = Charset.forName(UTF_8).newEncoder();
    private static CharsetDecoder decoder = Charset.forName(UTF_8).newDecoder();
    private CharsetHelper() {
    }
    public static ByteBuffer encode(CharBuffer in) throws CharacterCodingException{
      return encoder.encode(in);
    }
    public static CharBuffer decode(ByteBuffer in) throws CharacterCodingException{
      return decoder.decode(in);
    }
  }
}

看完上述內(nèi)容,你們掌握J(rèn)ava中的多線程回顯服務(wù)器怎么利用Socket實(shí)現(xiàn)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI