Skip to content

Commit dc8f4b4

Browse files
committed
feat: add client-side socket example and docs
1 parent d36e58a commit dc8f4b4

File tree

3 files changed

+294
-0
lines changed

3 files changed

+294
-0
lines changed
File renamed without changes.

05-Socket/README.md

Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
# Sockets in Java : Client-Side
2+
3+
A socket is a connection between two hosts.
4+
5+
Sockets provide a way for clients and servers to communicate over a network. In Java, the `Socket` class represents the client-side endpoint of a two-way communication link between a client and a server.
6+
7+
#### Key Concepts:
8+
- **Client-Server Communication**: A client socket connects to a server socket to exchange data.
9+
- **TCP Connection**: Sockets use the TCP protocol, ensuring reliable, ordered, and error-checked data transmission.
10+
- **Blocking Operations**: Socket operations like reading from or writing to a socket are blocking by default, meaning the program waits for the operation to complete.
11+
12+
## Socket Class
13+
14+
The `Socket` class in Java represents a **client-side socket** that connects to a server socket. It provides methods to send and receive data over the network.
15+
16+
## Constructors
17+
18+
### Basic Constructors
19+
20+
#### 1. Socket(String host, int port) throws Unknown Host Exception, IOException
21+
22+
```java
23+
Socket socket = new Socket("localhost", 8080);
24+
```
25+
26+
#### 2. Socket(InetAddress address, int port) throws IOException
27+
28+
```java
29+
InetAddress address = InetAddress.getByName("localhost");
30+
Socket socket = new Socket(address, 8080);
31+
```
32+
#### 3. Socket(String host, int port, InetAddress localAddr, int localPort) throws UnknownHostException, IOException
33+
34+
```java
35+
Socket socket = new Socket("localhost", 8080, InetAddress.getLocalHost(), 0);
36+
```
37+
#### 4. Socket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException
38+
39+
```java
40+
InetAddress address = InetAddress.getByName("localhost");
41+
Socket socket = new Socket(address, 8080, InetAddress.getLocalHost(), 0);
42+
```
43+
44+
### Proxy Constructors
45+
46+
This constructor is used to create a socket that connects through a specified proxy server.
47+
48+
#### 1. Socket(Proxy proxy) throws IOException
49+
50+
```java
51+
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
52+
53+
Socket socket = new Socket(proxy);
54+
```
55+
56+
#### 2. Socket(Proxy proxy, SocketAddress address) throws IOException
57+
58+
```java
59+
SocketAddress proxyAddress = new InetSocketAddress("proxy.example.com", 8080);
60+
61+
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
62+
63+
SocketAddress remote = new InetSocketAddress("example.com", 80);
64+
65+
Socket socket = new Socket(proxy, serverAddress);
66+
67+
socket.connect(remote);
68+
69+
```
70+
71+
### Constructing without Connecting
72+
73+
In some cases, you might want to create a socket without immediately connecting to a server. This approach gives you the flexibility to configure the socket before establishing the connection.
74+
75+
```java
76+
Socket socket = new Socket();
77+
78+
socket.connect(new InetSocketAddress("example.com", 80));
79+
```
80+
81+
82+
## Getting Socket Information
83+
84+
- `InetAddress getInetAddress()`: Returns the remote IP address to which the socket is connected.
85+
- `int getPort()`: Returns the remote port to which the socket is connected.
86+
- `InetAddress getLocalAddress()`: Returns the local IP address to which the socket is bound.
87+
- `int getLocalPort()`: Returns the local port to which the socket is bound.
88+
89+
90+
## Sending and Receiving Data
91+
92+
### Creating a Client Socket
93+
94+
To create a client socket, you typically connect to a server's IP address and port.
95+
96+
```java
97+
Socket socket = new Socket("server_ip", server_port);
98+
```
99+
100+
### Common Operations
101+
102+
1. **Connecting to a Server**
103+
```java
104+
Socket socket = new Socket("localhost", 8080);
105+
```
106+
- Connects to a server running on `localhost` at port `8080`.
107+
108+
2. **Sending Data to the Server**
109+
```java
110+
OutputStream output = socket.getOutputStream();
111+
PrintWriter writer = new PrintWriter(output, true);
112+
writer.println("Hello, Server!");
113+
```
114+
- Sends a message to the server.
115+
116+
3. **Receiving Data from the Server**
117+
```java
118+
InputStream input = socket.getInputStream();
119+
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
120+
String response = reader.readLine();
121+
System.out.println("Server response: " + response);
122+
```
123+
- Receives and prints the server's response.
124+
125+
4. **Closing the Connection**
126+
```java
127+
socket.close();
128+
```
129+
- Closes the socket and releases resources.
130+
131+
### Example: Simple Client
132+
133+
a simple client that connects to a server, sends a message, and prints the response.
134+
135+
```java
136+
import java.io.*;
137+
import java.net.Socket;
138+
139+
public class SimpleClient {
140+
141+
public static void main(String[] args) {
142+
String serverAddress = "localhost";
143+
int serverPort = 8080;
144+
145+
try (Socket socket = new Socket(serverAddress, serverPort);
146+
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
147+
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
148+
149+
// Send a message to the server
150+
writer.println("Hello, Server!");
151+
152+
// Read the server's response
153+
String response = reader.readLine();
154+
System.out.println("Server response: " + response);
155+
156+
} catch (IOException e) {
157+
e.printStackTrace();
158+
}
159+
}
160+
}
161+
```
162+
163+
### Key Points:
164+
- **Socket Initialization**: The client socket is initialized with the server’s address and port.
165+
- **I/O Streams**: `OutputStream` is used for sending data, and `InputStream` is used for receiving data.
166+
- **Exception Handling**: Sockets can throw `IOException`, so proper exception handling is necessary.
167+
- **Resource Management**: Always close the socket after communication is done to free resources.
168+
169+
170+
## Socket Options
171+
172+
Socket options specify how the native sockets on whicho the Java Socket class relies send and receive data. These options can be set using the `setOption()` method.
173+
174+
> Follow classic Unix C naming conventions
175+
176+
177+
### TCP_NODELAY
178+
Packets are sent as quickly as possible regardless of their size (even 1 byte)
179+
180+
```java
181+
public void setTcpNoDelay(boolean on) throws SocketException
182+
183+
// setTcpNoDelay(true) turns off buffering for the socket
184+
185+
public boolean getTcpNoDelay throws SocketException
186+
```
187+
188+
### SO_TIMEOUT
189+
Sets a timeout for blocking operations, such as reading from the socket. If the timeout is reached and no data has been received, a `SocketTimeoutException` is thrown.
190+
191+
```java
192+
public void setSoTimeout(int timeout) throws SocketException
193+
194+
// Set a timeout of 5000 milliseconds (5 seconds)
195+
socket.setSoTimeout(5000);
196+
197+
public int getSoTimeout() throws SocketException
198+
```
199+
This method returns the current timeout value in milliseconds.
200+
201+
### SO_LINGER
202+
Specifies how long the socket should wait to send remaining data when the socket is closed. The linger time can be set to ensure that data is not lost if the socket is closed abruptly.
203+
204+
```java
205+
public void setSoLinger(boolean on, int linger) throws SocketException
206+
207+
// setSoLinger(true, 10) sets the linger time to 10 seconds
208+
socket.setSoLinger(true, 10);
209+
210+
public int getSoLinger() throws SocketException
211+
```
212+
Returns the linger time in seconds. A return value of `-1` indicates that lingering is disabled.
213+
214+
### SO_KEEPALIVE
215+
Enables the sending of keep-alive messages on the connection. This is useful for detecting dead peers in a long-lived connection.
216+
217+
If turned on, the client occassionally sends a data packet over an idle connection to make sure the server hasn't crashed. Default is false.
218+
219+
```java
220+
public void setKeepAlive(boolean on) throws SocketException
221+
222+
// setKeepAlive(true) enables keep-alive messages
223+
socket.setKeepAlive(true);
224+
225+
public boolean getKeepAlive() throws SocketException
226+
```
227+
Returns whether the keep-alive option is enabled.
228+
229+
### SO_REUSEADDR
230+
Allows a socket to bind to a port that is already in use, which can be useful when restarting a server application or running multiple instances on the same machine.
231+
232+
```java
233+
public void setReuseAddress(boolean on) throws SocketException
234+
235+
// setReuseAddress(true) allows the reuse of a local address
236+
socket.setReuseAddress(true);
237+
238+
public boolean getReuseAddress() throws SocketException
239+
```
240+
Returns whether the `SO_REUSEADDR` option is enabled.
241+
242+
### SO_RCVBUF
243+
Sets the receive buffer size for the socket, which affects how much data can be buffered when receiving data from the network.
244+
245+
```java
246+
public void setReceiveBufferSize(int size) throws SocketException
247+
248+
// setReceiveBufferSize(8192) sets the receive buffer size to 8 KB
249+
socket.setReceiveBufferSize(8192);
250+
251+
public int getReceiveBufferSize() throws SocketException
252+
```
253+
Returns the current size of the receive buffer in bytes.
254+
255+
### SO_SNDBUF
256+
Sets the send buffer size for the socket, which affects how much data can be buffered when sending data over the network.
257+
258+
```java
259+
public void setSendBufferSize(int size) throws SocketException
260+
261+
// setSendBufferSize(8192) sets the send buffer size to 8 KB
262+
socket.setSendBufferSize(8192);
263+
264+
public int getSendBufferSize() throws SocketException
265+
```
266+
Returns the current size of the send buffer in bytes.
267+
268+
### SO_OOBINLINE
269+
The SO_OOBINLINE option controls how Out-of-Band (OOB) data is handled in a socket. Out-of-Band data is a special type of data that can be sent alongside normal data but is treated with higher priority. In the context of TCP/IP, OOB data is often used for urgent messages.
270+
271+
```java
272+
socket.setOOBInline(true);
273+
// Enables inline processing of OOB data
274+
275+
boolean isOOBInline = socket.getOOBInline();
276+
// Checks if OOBInline is enabled
277+
278+
public void sendUrgentData(int data) throws IOException;
279+
```
280+
281+
### IP_TOS
282+
Sets the Type of Service (TOS) or traffic class field in the IP header for packets sent by the socket. This option is used to specify the priority and quality of service for the network traffic.
283+
284+
```java
285+
public void setTrafficClass(int tc) throws SocketException
286+
287+
// setTrafficClass(0x10) sets the TOS field to a specific value
288+
socket.setTrafficClass(0x10);
289+
290+
public int getTrafficClass() throws SocketException
291+
```
292+
Returns the current value of the TOS field.
293+
294+
These options allow developers to fine-tune socket behavior according to their application's needs, providing control over performance, reliability, and data transmission characteristics.
File renamed without changes.

0 commit comments

Comments
 (0)