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

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

目前成都創(chuàng)新互聯(lián)已為1000+的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)頁空間、網(wǎng)站托管運營、企業(yè)網(wǎng)站設(shè)計、赤壁網(wǎng)站維護(hù)等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。

具體如下:

需要兩個類,一個是EchoServer,代表服務(wù)器。另外一個是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實現(xiàn)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

新聞名稱:Java中的多線程回顯服務(wù)器怎么利用Socket實現(xiàn)
本文地址:http://bm7419.com/article34/goejpe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、虛擬主機、微信小程序、網(wǎng)站制作App設(shè)計、品牌網(wǎng)站設(shè)計

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司