Java Socket Programming: Implement Bidirectional String Transfer Between Server and Client
This article explains how to use Java's java.net.Socket and ServerSocket classes to create a server and client that exchange string messages, detailing the blocking behavior of accept() and read(), and providing complete code examples for sending and receiving data in both directions.
Socket (套接字) is a communication abstraction that allows a computer to send and receive data over a network. In Java, the classes java.net.ServerSocket and java.net.Socket are used to build a server and a client.
Server side implementation
The server creates a ServerSocket on port 8088, calls accept() (which blocks until a client connects), obtains the input stream, reads characters into a buffer, prints the received strings, and finally closes all resources.
package com.badao;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) {
// Receive and print client‑sent string
getStringFromClient();
}
// Receive and read string from client
public static void getStringFromClient() {
try {
char[] charArray = new char[10];
ServerSocket serverSocket = new ServerSocket(8088);
System.out.println("accept begin = " + System.currentTimeMillis());
Socket socket = serverSocket.accept(); // blocks here
System.out.println("accept end = " + System.currentTimeMillis());
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
System.out.println("read begin = " + System.currentTimeMillis());
int readLength = inputStreamReader.read(charArray);
while (readLength != -1) {
String newString = new String(charArray, 0, readLength);
System.out.println(newString);
readLength = inputStreamReader.read(charArray);
}
System.out.println("read end = " + System.currentTimeMillis());
inputStreamReader.close();
inputStream.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}Running the server shows that it blocks at accept() until a client connects.
Client side implementation (client sends string)
The client creates a Socket that connects to localhost on port 8088, sleeps for three seconds, obtains the output stream, writes a UTF‑8 encoded string, and closes the connection.
package com.badao;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
// Client sends a string to the server
sendStringToServer();
}
// Client sends string to server
public static void sendStringToServer() throws IOException, InterruptedException {
System.out.println("socket begin =" + System.currentTimeMillis());
Socket socket = new Socket("localhost", 8088);
System.out.println("socket end =" + System.currentTimeMillis());
Thread.sleep(3000); // pause before sending
OutputStream outputStream = socket.getOutputStream();
outputStream.write("公众号:霸道的程序猿".getBytes());
outputStream.close();
socket.close();
}
}When the client runs, the server’s blocking accept() returns, the server reads the string, and the timestamps illustrate the blocking period.
Server sending string to client
To demonstrate bidirectional communication, the server can also write data to the client after accepting the connection.
// Server sends a string to the client
public static void sendStringToClient() throws IOException {
ServerSocket serverSocket = new ServerSocket(8088);
System.out.println("server堵塞开始 = " + System.currentTimeMillis());
Socket socket = serverSocket.accept();
System.out.println("server堵塞结束 = " + System.currentTimeMillis());
OutputStream outputStream = socket.getOutputStream();
outputStream.write("来自服务端-公众号:霸道的程序猿".getBytes());
outputStream.close();
socket.close();
serverSocket.close();
}Replace the call in main with sendStringToClient(); to let the server initiate the message.
Client receiving server data
The client mirrors the server’s receive logic, creating a socket, reading from the input stream, and printing the received string.
// Client receives string from server
public static void getStringFromServer() throws IOException {
System.out.println("client连接准备就绪 = " + System.currentTimeMillis());
Socket socket = new Socket("localhost", 8088);
System.out.println("client连接成功结束 = " + System.currentTimeMillis());
char[] charArray = new char[10];
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
System.out.println("read begin = " + System.currentTimeMillis());
int readLength = inputStreamReader.read(charArray);
while (readLength != -1) {
String newString = new String(charArray, 0, readLength);
System.out.println(newString);
readLength = inputStreamReader.read(charArray);
}
System.out.println("read end = " + System.currentTimeMillis());
inputStreamReader.close();
inputStream.close();
socket.close();
}Running the server first (which blocks on accept()) and then the client demonstrates the full round‑trip of string messages in both directions, as shown by the screenshots.
After the client connects, the server receives the client’s string, and the client can also receive the server’s reply when the server‑side method is switched to sendStringToClient().
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
