日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java 网络(socket)

發(fā)布時間:2025/4/9 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 网络(socket) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本文梳理一個基礎(chǔ)的java TCP消息通信,構(gòu)造一個簡單的Packet進(jìn)行傳輸,代碼如下:

  • Packet
public class Packet {private String attribute;public Packet(String attr){this.attribute = attr;}public String getAttribute() {return attribute;}public void setAttribute(String attribute) {this.attribute = attribute;} }
  • 服務(wù)器端代碼
public class App {private static final int PORT = 4000;public static void main(String[] args) throws IOException {ServerSocket listen = new ServerSocket(PORT);Socket client = null;while(true){client = listen.accept();new Thread(new ServerThread(client)).start();}} } public class ServerThread implements Runnable{private static final int BUFSIZE =1024;private Socket client = null;public ServerThread(Socket client){this.client = client;}@Overridepublic void run() {try {InputStream in = client.getInputStream();OutputStream out = client.getOutputStream();byte[] buffer = new byte[BUFSIZE];while (in.read(buffer) != -1) {//判斷包頭if(buffer[0] == 0x01 && buffer[1] == 0x02){byte[] tmp = new byte[BUFSIZE];int index = 0;for(int i = 2; i < buffer.length; i++){tmp[index++] = buffer[i];}Packet packet = new Packet(new String(tmp,"GB2312"));System.out.println(packet.getAttribute());}else{System.out.println("消息格式不正確");}}out.close();in.close();} catch (IOException e) {e.printStackTrace();} } }
  • 客戶端代碼
public class App {private static final int PORT = 4000;private static final int BUFSIZE =1024;public static void main(String[] args) throws IOException {Socket client = new Socket("127.0.0.1", PORT);InputStream in = client.getInputStream();OutputStream out = client.getOutputStream();Packet packet = new Packet("類型參數(shù)2345");byte[] output = new byte[BUFSIZE];output[0] = 0x01;output[1] = 0x02;int index = 2;//若增加包長度字段,則可實(shí)現(xiàn)packet的分包、組包byte[] tmp1 = packet.getAttribute().getBytes();for(int i= 0; i < tmp1.length; i++){output[index++] = tmp1[i];}out.write(output);byte[] buffer = new byte[BUFSIZE];while (in.read(buffer) != -1) { System.out.println(new String(buffer, "GB2312"));}out.close();in.close();client.close();} }

轉(zhuǎn)載于:https://www.cnblogs.com/Fredric-2013/p/4580688.html

總結(jié)

以上是生活随笔為你收集整理的java 网络(socket)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。