Socket Configuration Options

本文介绍了如何设置和获取Socket选项,包括保持连接活跃、重用地址以及广播设置。默认值由操作系统提供。设置SO_REUSEADDR选项允许在TIME_WAIT状态下绑定端口,以避免'地址已被使用'的错误。启用linger选项则可快速关闭套接字并重用地址,但可能导致数据丢失。
摘要由CSDN通过智能技术生成
Socket Configuration Options:

Socket options:

One can "get" (read) the current socket options or "set" them to new values. The default values are obtained from the OS:

Level Option Type Default Description
IPPROTO_IP TCP_NODELAY int 0 Don't delay send to coalesce packets. If set, disable the Nagle algorithm. When not set, data is buffered until there is a sufficient amount to send out, thereby avoiding the frequent sending of small packets, which results in poor utilization of the network. Don't use with TCP_CORK. This option is overridden by TCP_CORK
IPPROTO_IP TCP_MAXSEG int 536 Maximum segment size for outgoing TCP packets. TCP will impose its minimum and maximum bounds over the value provided.
IPPROTO_IP TCP_CORK int 0 Control sending of partial frames. If set, don't send out partial frames. Not cross platform.
IPPROTO_IP TCP_KEEPIDLE int 7200 When the SO_KEEPALIVE option is enabled, TCP probes a connection that has been idle for some amount of time. The default value for this idle period is 2 hours. The TCP_KEEPIDLE option can be used to affect this value for a given socket, and specifies the number of seconds of idle time between keepalive probes. 
Not cross platform. This option takes an int value, with a range of 1 to 32767.
IPPROTO_IP TCP_KEEPINTVL int 75 Specifies the interval between packets that are sent to validate the connection.
Not cross platform.
IPPROTO_IP TCP_KEEPCNT int 9 When the SO_KEEPALIVE option is enabled, TCP probes a connection that has been idle for some amount of time. If the remote system does not respond to a keepalive probe, TCP retransmits the probe a certain number of times before a connection is considered to be broken. The TCP_KEEPCNT option can be used to affect this value for a given socket, and specifies the maximum number of keepalive probes to be sent. This option takes an int value, with a range of 1 to 32767. Not cross platform.
IPPROTO_IP TCP_SYNCNT int 5 Number of SYN retransmits that TCP should send before aborting the attempt to connect. It cannot exceed 255.
IPPROTO_IP TCP_LINGER2 int 60 Life time of orphaned FIN-WAIT-2 state. Not to be confused with option SO_LINGER
Not cross platform.
SOL_SOCKET SO_REUSEADDR int
(bool)
0 Allow local address reuse. If a problem is encountered when attempting to bind to a port which has been closed but not released (may take up to 2 minutes as defined by TIME_WAIT). Apply the SO_REUSEADDR socket option to release the resource immediately and to get around the TIME_WAIT state.
0 = disables, 1 = enables
SOL_SOCKET SO_REUSEPORT int
(bool)
0 This option is AF_INET socket-specific. This option allows multiple processes to share a port. All incoming multicast or broadcast UDP datagrams that are destined for the port are delivered to all sockets that are bound to the port. All processes that share the port must specify this option.
0 = disables, 1 = enables
SOL_SOCKET SO_ERROR int
(bool)
0 When an error occurs on a socket, set error variable so_error and notify process
0 = disables, 1 = enables
SOL_SOCKET SO_BROADCAST int
(bool)
0 Permit sending of broadcast datagrams
0 = disables, 1 = enables
SOL_SOCKET SO_SNDBUF int
(value)
16384 Send buffer size
SOL_SOCKET SO_RCVBUF int
(value)
87380 Receive buffer size
SOL_SOCKET SO_KEEPALIVE int
(bool)
0 Periodically test if connection is alive
0 = disables, 1 = enables
SOL_SOCKET SO_SNDTIMEO timeval
(struct)
0
0
Set timeout period for socket send.
Disable by setting timeval.tv_sec = 0 sec, timeval.tv_usec = 0 usec (default)
Affects write() writev() send() sendto() and sendmsg()
SOL_SOCKET SO_RCVTIMEO timeval
(struct)
0
0
Set timeout period for socket receive.
Disable by setting timeval.tv_sec = 0 sec, timeval.tv_usec = 0 usec (default)
Affects read() readv() recv() recvfrom() and recvmsg()
SOL_SOCKET SO_LINGER linger
(struct)
0
0
Specifies how close function will operate for connection protocols (TCP)
l_onoff: 0 = disables, 1 = enables
l_linger: 0 = unsent data discarded, 1 = close() does not return untill all unsent data is transmitted or remote connection is closed
Structure defined in sys/socket.h
SOL_SOCKET SO_RCVLOWAT int
(value)
1 Specifies number of bytes used as a threshold by select() to consider a socket read ready
SOL_SOCKET SO_SNDLOWAT int
(value)
1 Specifies number of bytes used as a threshold by select() to consider a socket write ready
SOL_SOCKET SO_TYPE int
(value)
undefined Specifies socket type (e.g., tcp (SOCK_STREAM), udp (SOCK_DGRAM), etc.) 
For use with getsockopt() only.
IPPROTO_IP macro defines are found in  /usr/include/netinet/tcp.h 
SOL_SOCKET macro defines require  /usr/include/sys/socket.h

For a full list of options see the TCP man page

For a full list of IP options see the IP(7) man page

Function Prototypes:
int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen); 
int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen);

getsockopt/setsockopt arguments:
  • int sockfd: Socket file descriptor. Returned by call to "socket".
  • int level: See table above
  • int optname: See table above
  • void *optval: Pointer to value or data structure
  • optlen: Length of "optval"
  • Returns 0: Sucess, -1: Failure and errno may be set.

Code to read socket options:

File:  printSocketOptions.c
01 #include <sys/socket.h>
02 #include <netinet/in.h>
03 #include <netinet/tcp.h>
04 #include <errno.h>
05 #include <stdio.h>
06  
07 int main()
08 {
09    int socketHandle;
10  
11    // create socket
12  
13    if((socketHandle = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) < 0)
14    {
15       close(socketHandle);
16       perror("socket");
17    }
18  
19     int iSocketOption = 0;
20
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我可以给你一些示例代码,来帮助您编写socketio通信的Java服务端:import io.socket.client.IO; import io.socket.client.Socket; import io.socket.emitter.Emitter;public class SocketIOServer { public static void main(String[] args) { try { //创建socketio客户端 IO.Options opts = new IO.Options(); opts.forceNew = true; Socket socket = IO.socket("http://localhost:3000", opts); //连接到服务器 socket.connect(); //监听客户端发送的消息 socket.on("message", new Emitter.Listener() { public void call(Object... args) { System.out.println("收到消息:" + args[0]); } }); //发送消息到客户端 socket.emit("message", "Hello, I am your Server!"); } catch (Exception e) { e.printStackTrace(); } } } ### 回答2: 编写一个使用Socket.IO通信的Java服务端可以分为以下几个步骤: 第一步,导入所需的库和依赖。首先需要导入Java中的Socket和ServerSocket类,以及Socket.IO的Java客户端库。 ```java import java.io.*; import java.net.*; import io.socket.client.IO; import io.socket.client.Socket; ``` 第二步,创建一个服务器Socket,并监听指定的端口。 ```java int port = 3000; // 指定监听的端口号 ServerSocket serverSocket = new ServerSocket(port); ``` 第三步,接受客户端的连接请求,并创建一个新的Socket用于与客户端进行通信。 ```java Socket clientSocket = serverSocket.accept(); ``` 第四步,创建输入输出流以便与客户端进行数据传输。 ```java InputStream inputStream = clientSocket.getInputStream(); OutputStream outputStream = clientSocket.getOutputStream(); ``` 第五步,使用Socket.IO建立与客户端的连接,并定义事件监听器。 ```java String url = "http://localhost:3000"; // Socket.IO服务器的URL IO.Options options = new IO.Options(); options.forceNew = true; // 强制建立新连接 Socket socket = IO.socket(url, options); socket.on("eventName", new Emitter.Listener() { @Override public void call(Object... args) { // 处理收到的事件 } }); socket.connect(); ``` 第六步,使用输入输出流进行数据的读取和写入。 ```java // 从输入流中读取客户端发送的数据 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String message = reader.readLine(); // 向输出流中写入数据发送给客户端 PrintWriter writer = new PrintWriter(outputStream); writer.println("Hello, client!"); writer.flush(); ``` 第七步,关闭连接和释放资源。 ```java socket.disconnect(); // 关闭与客户端的Socket.IO连接 clientSocket.close(); // 关闭与客户端的Socket连接 serverSocket.close(); // 关闭服务器Socket ``` 以上是使用Socket.IO通信的Java服务端的基本步骤,根据实际需求可以进行相应的修改和扩展。 ### 回答3: 使用SocketIO通信的Java服务端代码示例如下: ```java import com.corundumstudio.socketio.*; import com.corundumstudio.socketio.listener.*; public class SocketIOServerExample { public static void main(String[] args) throws InterruptedException { Configuration config = new Configuration(); config.setHostname("localhost"); config.setPort(9092); final SocketIOServer server = new SocketIOServer(config); server.addEventListener("chatEvent", ChatObject.class, new DataListener<ChatObject>() { @Override public void onData(SocketIOClient client, ChatObject chatObject, AckRequest ackRequest) { // 处理收到的消息 System.out.println("Received message: " + chatObject.getMessage()); // 回复客户端消息 server.getBroadcastOperations().sendEvent("chatEvent", chatObject); } }); server.start(); Thread.sleep(Integer.MAX_VALUE); server.stop(); } } class ChatObject { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } ``` 在上面的示例中,我们使用了SocketIO库,它提供了一个SocketIOServer类,用于创建和管理SocketIO服务器。我们配置了服务器的主机名为localhost和端口号为9092,并创建了一个实例化的SocketIOServer对象。 然后,我们使用`addEventListener`方法注册了一个名为"chatEvent"的事件,并通过ChatObject类指定了监听器的数据类型。当服务器收到名为"chatEvent"的消息时,会调用相应的监听器进行处理。在监听器中,我们打印收到的消息,并使用SocketIO服务器的`getBroadcastOperations`方法回复相同的消息给客户端。 最后,我们通过调用`start`方法启动SocketIO服务器,并使用`Thread.sleep`将主线程挂起,以保持服务器运行。当我们想停止服务器时,可以调用`stop`方法。 这是一个简单的使用SocketIO通信的Java服务端示例,你可以根据需要增加其他事件和处理逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值