Java Socket編程執行個體(一)- TCP基本使用_java

來源:互聯網
上載者:User

一.服務端代碼:

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 中文參考手冊》,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.