Setsocket usage (transferred from GDY users of 9CBS)

xiaoxiao2021-03-05  31

Reposted from 9CBS GDY netizen works, thank you.

Original Address: http://community.9cbs.net/expert/topic/3592/3592436.xml? Temp = .2238275 Constantly received Coolmei25 (Mei Sheng) thank you, I am embarrassed (I didn't help He), let's write a little experience in the network programming, I hope to help him (^ _ ^ also to everyone): 1. If the socket is already in the Established state (generally distinguished by the port number and flag ) Calling CloseSocket (generally not immediately shutting down) After experiencing Time_Wait procedure, you want to continue to reuse the socket: Bool BreuseAddr = true; setsockopt (s, s, s, s, s, s, (const char *) & breuseaddr, sizeof (bool)); 2. If SOKET is already in connection, it is forced to turn off after calling CloseSocket, and does not experience the process of time_wait: BOOL BDONTLINGER = FALSE; Setsockopt (S, SOL_Socket, SO_DONTLINGER, (const char *) & bdontlinger, sizeof (bool); 3. Send (), the Recv () is sometimes due to network conditions, etc., the revenue cannot be performed, and the delivery time limit is set: int nnettimeout = 1000; // 1 second // Send time limit setsockopt (socket, SOL_S0CKET, SO_SNDTIMEO, (char *) & nnettimeout, sizeof (int)); // Receive time limit setsockopt (socket, sol_s0cket, so_rcvtimeo, (char *) & nnettimeout, sizeof (int)); 4. When Send (), returns to actually send out Byte (synchronous) or byte (asynchronous) sent to the socket buffer; system default status transmission and reception of 8688 bytes (approximately 8.5k); send data and receive data in the actual process You can set the Socket buffer to avoid send (), RECV () constant loop transceiver: // Receive buffer int NRECVBUF = 32 * 1024; // Set to 32ksetSockopt (S, SOL_Socket, SO_RCVBUF, (const char * ) & nrecvbuf, sizeof (int)); // Send buffer INT NsendBuf = 32 * 1024; // Set to 32ksetSockopt (S, SOL_Socket, SO_SNDBUF, (const char *) & nsendbuf, sizeof (int)); 5. If you send data, you want to pass the system buffer to the socket buffer. Copy of the area affects the performance of the program: int Nzero = 0; setsockopt (socket, sol_s0cket, so_sndbuf, (char *) & nzero, sizeof (nzero)); 6. To complete the above function in RECV () (by default is Socket The contents of the buffer are copied to the system buffer): int Nzero = 0; setsockopt (socket, sol_s0cket, so_rcvbuf, (char *) & nzero, sizeof (int)); 7. When sending UDP datagrams, I hope that Socket The transmitted data has broadcast features: bool bbroadcast = true; setsockopt (s, sol_socket, so_broadcast, (const char *) &

BBroadcast, SizeOf (BOOL)); 8. During the client connection server, if the socket in non-blocking mode can set the connect () delay in the process () process until the ACCPET () is called (this function setting There is only a significant role in the process of non-blocking, and there is little effect in the blocking function calls) BOOL BCONDITALACCEPT = true; setsockopt (S, SOL_SOCKET, SO_CONDITIONAL_ACCEPT, (const char *) & bconditionaCcept, SizeOf (bool)); 9. If the data is not sent during the transmission of data (Send () is not sent), there is no transmission of the data (), which we generally taken "Shutdown (S, SD_BOTH), but data is definitely lost How to set up the request to meet the requirements of the specific application (ie, let the data that have not been sent out after closing the socket)? Struct linger {u_short l_onoff; u_short l_linger;}; linger m_slinger; m_slinger.l_onoff = 1; // (in closesocket () call, but there is a time to stay when it is not sent) // If m_slinger.l_onoff = 0; The function and 2.) the same effect; m_slinger.l_linger = 5; // (allowed to stay at 5 seconds) Setsockopt (S, SOL_Socket, SO_Linger, (const char *) & m_slinger, sizeof (linger)); Note: 1 At setting a stay delay, a non-blocking socket is not a lot, it is best not to use; 2. If you want a program that does not experience SO_Linger, you need to set SO_DONTLINGER, or set l_onoff = 0; 10. Small is the SDI or Dialog's program, you can record the status of Socket: (Test of this function, the adjustment information can be saved, including the parameters of Socket, the specific protocol, and error The code can be recorded) Bool BDebug = true; setsockopt (S, SOL_Socket, SO_Debug, (const char *) & bdebug, sizeof (bool)); 11. Additional: The buffer size is often set by setsockopt (), but not Meet the data transmission needs, my habits are written by handling the network buffer, dynamically allocate memory; I will write this class, I hope to help beginners:

/ / 照照 照照 写 写 写 写 写 写 写 写 写 写 写 写 照 写 照 照 写 照 照 照 照 照 照 照 照 照 照 照 照 照 照 照 照============================================== // binary data is mainly used to send and receive network buffers Data // CNetiobuffer is rewritten as the source code of MFC class CString, and the usage is similar to CString, // But the pure binary data is stored in CNetiobuffer, '/ 0' does not act as its end sign. // The length of its data can be obtained by getLength (), the buffer address can be obtained by operator LPBYTE.

/ / =========================================================================================================================================================================================== ============================== // CopyRight (c) all-vision corporation. All rights reserved.// module: netobject // file: Simpleiobuffer.h // Author: gdy119 // email: 8751Webmaster@126.com// Date: 2004.11.26 / / ====================== ============================================================================================================================================================================================================= ======== // Netiobuffer.h # ifNDef _netiobuffer_h # define _netiobuffer_h // ============================= ================================================= # Define MAX_BUFFER_LENGTH 1024 * 1024 / / ============================================== =============

==================== // Mainly used to process network buffer data class cNetiobuffer {protected: lpbyte m_pbindata; int m_nlength; int m_ntotallength; critical_sectionm_cs; voidinitvalibers () Public: cNetiobuffer (); CNetiobuffer (const lpbyte lbyte, int nlength); CNetiobuffer (const cnetiobuffer & binarysrc); virtual ~ cNetiobuffer (); // =================== ============================================================================================================================================================================================================= ======== BOOL CopyData (const LPBYTE lbbyte, int nLength); BOOL ConcatData (const LPBYTE lbbyte, int nLength); void ResetIoBuffer (); int GetLength () const; BOOL SetLength (int nLen); LPBYTE GetCurPos (); int GetRemainLen (); BOOL IsEmpty () const; operator LPBYTE () const; static getMaxLength () {return MAX_BUFFER_LENGTH;} const CNetIOBuffer & operator = (const CNetIOBuffer & buffSrc);}; # endif // // NetOBuffer.cpp : Implementation of the cNetiobuffer Class.//========================================= ============================= # incrude "stdafx.h" #include "Netiobuffer.h" / / ======

============================================================================================================================================================================================================= ======================================================================================================================================================= ============================================== // Construction / DestructionCnetiobuffer :: CNetiobuffer () {initvalibers );} CNetIOBuffer :: CNetIOBuffer (const LPBYTE lbbyte, int nLength) {Initvalibers (); CopyData (lbbyte, nLength);} CNetIOBuffer :: ~ CNetIOBuffer () {delete [] m_pbinData; m_pbinData = NULL; DeleteCriticalSection (& m_cs);

} CNETIOBUFFER :: CNetiobuffer (Const CNetiobuffer & BinarySrc) {

INITVALIBERS (); CopyData (binarysrc, binarysrc.getLength ());

} void CNetiobuffer :: initvalibers () {

m_pbinData = NULL; m_nLength = 0; m_nTotalLength = MAX_BUFFER_LENGTH; if (m_pbinData == NULL) {m_pbinData = new BYTE [m_nTotalLength]; ASSERT (m_pbinData = NULL!);} InitializeCriticalSection (& m_cs);} void CNetIOBuffer :: ResetIoBuffer () {ENTERCRITICALSECTION (& M_CS); m_nlength = 0; Memset (M_PBINDATA, 0, M_NTOTATIONENGTH); LeaveCriticalSection (& M_CS);

Bool CNETIOBUFFER :: CopyData (const lpbyte lbyte, int nlength) {if (NLENGTH> MAX_BUFFER_LENGTH) RETURN FALSE

Resetiobuffer (); EntercriticalSection; Memcpy (M_PBINDATA, LBBBYTE, NLENGTH); M_NLENGTH = NLENGTH; LeavecriticalSection (& M_CS); Return True;

BOOL CNETIOBUFFER :: Constdata (const nlength) {if (m_nlength nlength> max_buffer_ley) Return False;

ENTERCRITICALSECTION; Memcpy (m_pbindata m_nlength; m_nlength = NLENGTH; LeavecriticalSection;

Return True;}

INT CNETIOBUFFER :: getLength () const {return m_nlength;}

Bool CNetiobuffer :: SETLENGTH (INT NLEN) {IF (Nlen> Max_Buffer_Length) Return False;

ENTERCRITICALSECTION (& M_CS); m_nlength = Nlen; LeaveCriticalSection (& M_CS);

Return True;}

LPBYTE CNETIOBUFFER :: getcurpos () {

IF (m_nlength

Return (M_PBINDATA M_NLENGTH);

Elsereturn null;}

CNETIOBUFFER :: Operator lpbyte () const {return m_pbindata;}

INT CNETIOBUFFER :: getRemainlen () {

RETURN MAX_BUFFER_LENGTH - M_NLENGTH;

} BOOL CNETIOBUFFER :: ISEMPTY () const {return m_nlength == 0;

Const CNetiobuffer & CNetiobuffer :: Operator = (Const CNetiobuffer & Buffsrc) {IF (& Buffsrc! = this) {CopyData (buffsrc, buffsrc.getLength);

} Return * this;

}

转载请注明原文地址:https://www.9cbs.com/read-33313.html

New Post(0)