Java Socket Class
A Socket is the basic building block of network communication, allowing data exchange between different computers over a network.
In Java,java.net.Socket The class provides client-side functionality for network communication.
You can think of a Socket as a connection between two telephones:
- One end is the client (the caller)
- The other end is the server (the one answering the call)
- Once the connection is established, both parties can send and receive information to and from each other
Basic Usage of the Socket Class
Creating a Socket Connection
To create a Socket connection, you need to specify the server's address and port:
Example
try
{
// Connect to localhost on port 8080
Socket
socket
=
new
Socket
(
"localhost"
,
8080
)
;
// Communicate using the socket...
// Close the connection
socket.
close
(
)
;
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
Main methods
The Socket class provides several important methods:
| Method | Description |
|---|---|
getInputStream() |
Get the input stream, used to receive data |
getOutputStream() |
Get the output stream, used to send data |
close() |
Close the Socket connection |
isConnected() |
Check whether the connection is established |
setSoTimeout(int timeout) |
Set the timeout (in milliseconds) |
Implementing Client-Server Communication
Client Example
Example
import
java.io.*
;
import
java.net.*
;
public
class
Client
{
public
static
void
main
(
String
[
]
args
)
{
try
{
// 1. Create a Socket connection
Socket
socket
=
new
Socket
(
"localhost"
,
12345
)
;
// 2. Get the output stream and send data to the server
PrintWriter
out
=
new
PrintWriter
(
socket.
getOutputStream
(
)
,
true
)
;
out.
println
(
"Hello Server!"
)
;
// 3. Get the input stream and receive the server's response
BufferedReader
in
=
new
BufferedReader
(
new
InputStreamReader
(
socket.
getInputStream
(
)
)
)
;
String
response
=
in.
readLine
(
)
;
System
.
out
.
println
(
"Server response: "
response
)
;
// 4. Close the connection
socket.
close
(
)
;
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
}
}
Server Example
The server side needs to use ServerSocket class:
Example
import
java.io.*
;
import
java.net.*
;
public
class
Server
{
public
static
void
main
(
String
[
]
args
)
{
try
{
// 1. Create a ServerSocket and listen on the specified port
ServerSocket
serverSocket
=
new
ServerSocket
(
12345
)
;
System
.
out
.
println
(
"Server started. Waiting for client..."
)
;
// 2. Wait for a client connection
Socket
clientSocket
=
serverSocket.
accept
(
)
;
System
.
out
.
println
(
"Client connected."
)
;
// 3. Get the input stream and read the client's message
BufferedReader
in
=
new
BufferedReader
(
new
InputStreamReader
(
clientSocket.
getInputStream
(
)
)
)
;
String
message
=
in.
readLine
(
)
;
System
.
out
.
println
(
"Client says: "
message
)
;
// 4. Get the output stream and send a response to the client
PrintWriter
out
=
new
PrintWriter
(
clientSocket.
getOutputStream
(
)
,
true
)
;
out.
println
(
"Hello Client!"
)
;
// 5. Close the connection
clientSocket.
close
(
)
;
serverSocket.
close
(
)
;
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
}
}
Advanced Features of Socket
Setting Timeouts
Example
Socket
socket
=
new
Socket
(
)
;
// Set the connection timeout to 5 seconds
socket.
connect
(
new
InetSocketAddress
(
"example.com"
,
80
)
,
5000
)
;
// Set the read timeout to 3 seconds
socket.
setSoTimeout
(
3000
)
;
Keep-Alive
Example
// Enable the TCP keep-alive mechanism
socket.
setKeepAlive
(
true
)
;
Buffer Size
Example
// Set the receive buffer size (in bytes)
socket.
setReceiveBufferSize
(
8192
)
;
// Set the send buffer size (in bytes)
socket.
setSendBufferSize
(
8192
)
;
Common Problems and Solutions
Connection Refused
- Check whether the server is running
- Confirm that the port number is correct
- Check the firewall settings
Connection Timeout
- Check the network connection
- Increase the timeout
- Confirm that the server address is correct
Incomplete Data Reception
- Ensure both sides use the same protocol
- Check whether the buffer size is sufficient
- Consider using delimiters or fixed-length messages
Practical Application Scenarios
Socket programming has wide practical applications:
- Instant messaging applications (such as WeChat, QQ)
- Online games
- Remote control software
- File transfer tools
- IoT device communication
Best Practices
- Always handle IO exceptions
- Use try-with-resources to ensure resources are released
- Set reasonable timeouts for important operations
- Consider using a thread pool to handle multiple connections
- Design a clear communication protocol