Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Socket Class

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:


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

Connection Timeout

Incomplete Data Reception


Practical Application Scenarios

Socket programming has wide practical applications:


Best Practices

  1. Always handle IO exceptions
  2. Use try-with-resources to ensure resources are released
  3. Set reasonable timeouts for important operations
  4. Consider using a thread pool to handle multiple connections
  5. Design a clear communication protocol