服务器之家

服务器之家 > 正文

Java Socket编程实例(一)- TCP基本使用

时间:2020-05-16 16:05     来源/作者:kingxss

一.服务端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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 */
  }
}

二.客户端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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的语法,也希望大家多多支持服务器之家。

标签:

相关文章

热门资讯

歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
返回顶部