最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java基于socket實(shí)現(xiàn)的客戶端和服務(wù)端通信功能完整實(shí)例

 更新時(shí)間:2018年05月23日 11:57:56   作者:愛代碼也愛生活  
這篇文章主要介紹了Java基于socket實(shí)現(xiàn)的客戶端和服務(wù)端通信功能,結(jié)合完整實(shí)例形式分析了Java使用socket建立客戶端與服務(wù)器端連接與通信功能,需要的朋友可以參考下

本文實(shí)例講述了Java基于socket實(shí)現(xiàn)的客戶端和服務(wù)端通信功能。分享給大家供大家參考,具體如下:

以下代碼參考馬士兵的聊天項(xiàng)目,先運(yùn)行ChatServer.java實(shí)現(xiàn)端口監(jiān)聽,然后再運(yùn)行ChatClient.java

客戶端實(shí)例

ChatClient.java

package socketDemo;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
  Socket s = null;
  DataOutputStream dos = null;
  DataInputStream dis = null;
  private boolean bConnected = false;
  TextField tfTxt = new TextField();
  TextArea taContent = new TextArea();
  Thread tRecv = new Thread(new RecvThread());
  public static void main(String[] args) {
    new ChatClient().launchFrame();
  }
  public void launchFrame() {
    setLocation(400, 300);
    this.setSize(300, 300);
    add(tfTxt, BorderLayout.SOUTH);
    add(taContent, BorderLayout.NORTH);
    pack();
    this.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent arg0) {
        disconnect();
        System.exit(0);
      }
    });
    tfTxt.addActionListener(new TFListener());
    setVisible(true);
    connect();
    tRecv.start();
  }
  public void connect() {
    try {
      s = new Socket("localhost", 8888);
      dos = new DataOutputStream(s.getOutputStream());
      dis = new DataInputStream(s.getInputStream());
      System.out.println("connected!");
      bConnected = true;
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public void disconnect() {
    try {
      dos.close();
      dis.close();
      s.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    /*
     * try { bConnected = false; tRecv.join(); } catch(InterruptedException
     * e) { e.printStackTrace(); } finally { try { dos.close(); dis.close();
     * s.close(); } catch (IOException e) { e.printStackTrace(); } }
     */
  }
  private class TFListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String str = tfTxt.getText().trim();
      // taContent.setText(str);
      tfTxt.setText("");
      try {
        // System.out.println(s);
        dos.writeUTF(str);
        dos.flush();
        // dos.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
  private class RecvThread implements Runnable {
    public void run() {
      try {
        while (bConnected) {
          String str = dis.readUTF();
          // System.out.println(str);
          taContent.setText(taContent.getText() + str + '\n');
        }
      } catch (SocketException e) {
        System.out.println("退出了,bye!");
      } catch (EOFException e) {
        System.out.println("推出了,bye - bye!");
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

socket服務(wù)端代碼

ChatServer.java

package socketDemo;
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
  boolean started = false;
  ServerSocket ss = null;
  List<Client> clients = new ArrayList<Client>();
  public static void main(String[] args) {
    new ChatServer().start();
  }
  public void start() {
    try {
      ss = new ServerSocket(8888);
      started = true;
    } catch (BindException e) {
      System.out.println("端口使用中....");
      System.out.println("請(qǐng)關(guān)掉相關(guān)程序并重新運(yùn)行服務(wù)器!");
      System.exit(0);
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      while (started) {
        Socket s = ss.accept();
        Client c = new Client(s);
        System.out.println("a client connected!");
        new Thread(c).start();
        clients.add(c);
        // dis.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        ss.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  class Client implements Runnable {
    private Socket s;
    private DataInputStream dis = null;
    private DataOutputStream dos = null;
    private boolean bConnected = false;
    public Client(Socket s) {
      this.s = s;
      try {
        dis = new DataInputStream(s.getInputStream());
        dos = new DataOutputStream(s.getOutputStream());
        bConnected = true;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    public void send(String str) {
      try {
        dos.writeUTF(str);
      } catch (IOException e) {
        clients.remove(this);
        System.out.println("對(duì)方退出了!我從List里面去掉了!");
        // e.printStackTrace();
      }
    }
    public void run() {
      try {
        while (bConnected) {
          String str = dis.readUTF();
          System.out.println(str);
          for (int i = 0; i < clients.size(); i++) {
            Client c = clients.get(i);
            c.send(str);
            // System.out.println(" a string send !");
          }
          /*
           * for(Iterator<Client> it = clients.iterator();
           * it.hasNext(); ) { Client c = it.next(); c.send(str); }
           */
          /*
           * Iterator<Client> it = clients.iterator();
           * while(it.hasNext()) { Client c = it.next(); c.send(str);
           * }
           */
        }
      } catch (EOFException e) {
        System.out.println("Client closed!");
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          if (dis != null)
            dis.close();
          if (dos != null)
            dos.close();
          if (s != null) {
            s.close();
            // s = null;
          }
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
    }
  }
}

本機(jī)測(cè)試運(yùn)行結(jié)果:

關(guān)閉客戶端窗口后,提示信息如下:

更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java Socket編程技巧總結(jié)》、《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • Java 多線程學(xué)習(xí)詳細(xì)總結(jié)

    Java 多線程學(xué)習(xí)詳細(xì)總結(jié)

    本文主要介紹 Java 多線程的知識(shí)資料,這里整理了詳細(xì)的多線程內(nèi)容,及簡(jiǎn)單實(shí)現(xiàn)代碼,有需要的朋友可以參考下
    2016-09-09
  • java注解結(jié)合aspectj AOP進(jìn)行日志打印的操作

    java注解結(jié)合aspectj AOP進(jìn)行日志打印的操作

    這篇文章主要介紹了java注解結(jié)合aspectj AOP進(jìn)行日志打印的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • springboot 熱啟動(dòng)的過(guò)程圖解

    springboot 熱啟動(dòng)的過(guò)程圖解

    這篇文章主要介紹了springboot 熱啟動(dòng)的過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • struts2實(shí)現(xiàn)文件下載功能

    struts2實(shí)現(xiàn)文件下載功能

    這篇文章主要為大家詳細(xì)介紹了struts2實(shí)現(xiàn)文件下載功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • Java HashMap源碼及并發(fā)環(huán)境常見問(wèn)題解決

    Java HashMap源碼及并發(fā)環(huán)境常見問(wèn)題解決

    這篇文章主要介紹了Java HashMap源碼及并發(fā)環(huán)境常見問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-09-09
  • JAVA調(diào)用JavaScript方法舉例詳解

    JAVA調(diào)用JavaScript方法舉例詳解

    之前在一次機(jī)緣巧合的情況下,需要時(shí)用JAVA執(zhí)行js方法,查閱了一些文檔,找到了相關(guān)解決方法,這里和大家分享一下,下面這篇文章主要給大家介紹了關(guān)于JAVA調(diào)用JavaScript方法的相關(guān)資料,需要的朋友可以參考下
    2023-10-10
  • Spring 異常處理的各種姿勢(shì)總結(jié)

    Spring 異常處理的各種姿勢(shì)總結(jié)

    這篇文章主要介紹了Spring 異常處理,總結(jié)分析了Spring 異常處理的各種常見操作技巧與相關(guān)使用注意事項(xiàng),需要的朋友可以參考下
    2020-05-05
  • JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載實(shí)例解析

    JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載實(shí)例解析

    這篇文章主要介紹了JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載的相關(guān)資料,需要的朋友可以參考下
    2016-02-02
  • Java可重入鎖的實(shí)現(xiàn)示例

    Java可重入鎖的實(shí)現(xiàn)示例

    在java中,可重入鎖分為兩種,即synchronized鎖以及ReentrantLock及其實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-02-02
  • java HttpClient傳輸json格式的參數(shù)實(shí)例講解

    java HttpClient傳輸json格式的參數(shù)實(shí)例講解

    這篇文章主要介紹了java HttpClient傳輸json格式的參數(shù)實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-01-01

最新評(píng)論

咸丰县| 莱州市| 区。| 江川县| 浑源县| 清远市| 乌拉特后旗| 滨海县| 石景山区| 即墨市| 大埔区| 百色市| 纳雍县| 双柏县| 昌吉市| 延长县| 鄂温| 治多县| 西和县| 江都市| 平安县| 贡嘎县| 武安市| 武鸣县| 武邑县| 宣恩县| 德兴市| 承德市| 通渭县| 大洼县| 安仁县| 巴中市| 江孜县| 简阳市| 杭锦后旗| 项城市| 白城市| 晋中市| 固始县| 茂名市| 罗江县|