Java Socket 프로그래밍 인스턴스(1) - TCP 기본 사용

3449 단어 JavaSocketTCP
하나.서버 코드:

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 */ 
  } 
} 
2.클라이언트 코드:

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 자바 중국어 참조 안내서 》,많은 응원 부탁드립니다.

좋은 웹페이지 즐겨찾기