国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java Socket編程實例(一)- TCP基本使用

2019-11-26 14:11:40
字體:
來源:轉載
供稿:網友

一.服務端代碼:

import java.net.*; // for Socket, ServerSocket, and InetAddress import java.io.*; // for IOException and Input/OutputStream  public class TCPEchoServer {    private static final int BUFSIZE = 32; // Size of receive buffer    public static void main(String[] args) throws IOException {      int servPort = 5500;      // Create a server socket to accept client connection requests     ServerSocket servSock = new ServerSocket(servPort);      int recvMsgSize; // Size of received message     byte[] receiveBuf = new byte[BUFSIZE]; // Receive buffer      while (true) { // Run forever, accepting and servicing connections       Socket clntSock = servSock.accept(); // Get client connection        SocketAddress clientAddress = clntSock.getRemoteSocketAddress();       System.out.println("Handling client at " + clientAddress);        InputStream in = clntSock.getInputStream();       OutputStream out = clntSock.getOutputStream();        // Receive until client closes connection, indicated by -1 return       while ((recvMsgSize = in.read(receiveBuf)) != -1) {         out.write(receiveBuf, 0, recvMsgSize);       }        clntSock.close(); // Close the socket. We are done with this client!     }     /* NOT REACHED */   } } 

二.客戶端代碼:

import java.net.*; import java.io.*;  public class TCPEchoClient {    public static void main(String[] args) throws IOException {      String server = "127.0.0.1"; // Server name or IP address     int servPort = 5500; //// Server port     byte[] data = "Hi, World".getBytes();      // Create socket that is connected to server on specified port     Socket socket = new Socket(server, servPort);     System.out.println("Connected to server...sending echo string");      InputStream in = socket.getInputStream();     OutputStream out = socket.getOutputStream();      out.write(data); // Send the encoded string to the server      // Receive the same string back from the server     int totalBytesRcvd = 0; // Total bytes received so far     int bytesRcvd; // Bytes received in last read     while (totalBytesRcvd < data.length) {       if ((bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd)) == -1)         throw new SocketException("Connection closed prematurely");       totalBytesRcvd += bytesRcvd;     } // data array is full      System.out.println("Received: " + new String(data));     socket.close(); // Close the socket and its streams   } } 

上述代碼的TCP服務端是單線程,一次只能服務一個客戶端。

查看更多Java的語法,大家可以關注:《Thinking in Java 中文手冊》、《JDK 1.7 參考手冊官方英文版》、《JDK 1.6 API java 中文參考手冊》、《JDK 1.5 API java 中文參考手冊》,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 开远市| 洱源县| 八宿县| 沭阳县| 荃湾区| 本溪市| 安岳县| 绥芬河市| 新源县| 安陆市| 麻栗坡县| 金昌市| 丁青县| 怀远县| 舞钢市| 四平市| 弥勒县| 武川县| 改则县| 林甸县| 耒阳市| 五台县| 丽江市| 平定县| 寿光市| 岑溪市| 阿瓦提县| 汪清县| 七台河市| 连云港市| 曲阳县| 富源县| 清远市| 贵港市| 河西区| 武宁县| 三亚市| 苍山县| 龙陵县| 平舆县| 鲁山县|