0
点赞
收藏
分享

微信扫一扫

java tcp server client

辰鑫chenxin 2023-07-17 阅读 66

Java TCP Server and Client

In computer networking, TCP (Transmission Control Protocol) is a reliable and connection-oriented protocol that allows two applications to establish a communication channel and exchange data. In this article, we will explore how to create a TCP server and client using Java.

TCP Server

A TCP server listens for incoming connections from clients and responds to their requests. Here is an example of a simple TCP server in Java:

import java.io.*;
import java.net.*;

public class TCPServer {
    public static void main(String[] args) {
        try {
            // Create a server socket
            ServerSocket serverSocket = new ServerSocket(8888);
            
            System.out.println("Server listening on port 8888...");
            
            while (true) {
                // Accept a client connection
                Socket clientSocket = serverSocket.accept();
                
                System.out.println("Client connected from " + clientSocket.getInetAddress().getHostAddress());
                
                // Create input and output streams for the client socket
                InputStream inputStream = clientSocket.getInputStream();
                OutputStream outputStream = clientSocket.getOutputStream();
                
                // Read data from the client
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String requestData = reader.readLine();
                System.out.println("Received data from client: " + requestData);
                
                // Send response to the client
                String responseData = "Hello from server!";
                PrintWriter writer = new PrintWriter(outputStream, true);
                writer.println(responseData);
                
                // Close the client socket
                clientSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above code, we create a ServerSocket object and bind it to port 8888. We then enter a continuous loop to accept client connections. For each connection, we create input and output streams to communicate with the client. We read data from the client using a BufferedReader and send a response back using a PrintWriter. Finally, we close the client socket.

TCP Client

A TCP client initiates a connection to a TCP server and sends requests to it. Here is an example of a TCP client in Java:

import java.io.*;
import java.net.*;

public class TCPClient {
    public static void main(String[] args) {
        try {
            // Create a client socket and connect to the server
            Socket clientSocket = new Socket("localhost", 8888);
            
            // Create input and output streams for the client socket
            InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream();
            
            // Send request to the server
            String requestData = "Hello from client!";
            PrintWriter writer = new PrintWriter(outputStream, true);
            writer.println(requestData);
            
            // Read response from the server
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String responseData = reader.readLine();
            System.out.println("Received response from server: " + responseData);
            
            // Close the client socket
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above code, we create a Socket object and connect it to the server running on the localhost at port 8888. We then create input and output streams to communicate with the server. We send a request to the server using a PrintWriter and read the response using a BufferedReader. Finally, we close the client socket.

Running the Server and Client

To run the TCP server and client, follow these steps:

  1. Compile the TCPServer.java and TCPClient.java files using the Java compiler: javac TCPServer.java TCPClient.java.
  2. Start the server by running the TCPServer class: java TCPServer.
  3. Start the client by running the TCPClient class: java TCPClient.

You should see the server listening on port 8888 and the client connecting to the server. The client will send a request to the server, and the server will respond with a message. The client will display the response received from the server.

Conclusion

In this article, we have learned how to create a simple TCP server and client using Java. The server listens for incoming connections and responds to client requests, while the client initiates a connection and sends requests to the server. TCP provides a reliable and connection-oriented communication channel between applications, allowing them to exchange data seamlessly. TCP is widely used in various networking applications, such as web browsing, email, and file transfer.

举报

相关推荐

0 条评论