TCP Socket程式設計(非阻塞模式)(C )

2021-07-31 01:17:29 字數 3011 閱讀 1732

伺服器:

// tcpserver.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include #include #pragma comment(lib,"ws2_32.lib")

#define buf_size 64

int _tmain(int argc, _tchar* argv)

//建立用於監聽的socket

sserver = socket(af_inet,sock_stream,ipproto_tcp);

if (invalid_socket == sserver)

//設定socket為非阻塞模式

int imode = 1;

retval = ioctlsocket(sserver,fionbio,(u_long far*)&imode);

if (retval == socket_error)

//設定伺服器socket位址

sockaddr_in addrserv;

addrserv.sin_family = af_inet;

addrserv.sin_port = htons(9990);

addrserv.sin_addr.s_un.s_addr = htonl(inaddr_any);

//繫結socket server到本地位址

retval = bind(sserver,(const struct sockaddr*)&addrserv,sizeof(sockaddr_in));

if (retval == socket_error)

//監聽

retval = listen(sserver,1);

if (retval == socket_error)

//接受客戶請求

printf("tcp server start...\n");

sockaddr_in addrclient;

int addrclientlen = sizeof(addrclient);

//迴圈等待

while (true)

else

} break;

} //迴圈接受客戶端的資料,直到客戶端傳送quit命令後退出

while (true)

else if (err == wsaetimedout || err == wsaenetdown)

}//獲取系統時間

systemtime st;

getlocaltime(&st);

char sdatetime[30];

sprintf_s(sdatetime, "%4d-%2d-%2d %2d:%2d:%2d", st.wyear, st.wmonth, st.wday, st.whour, st.wminute, st.wsecond);

//列印輸出資訊

printf("%s,recv from client [%s:%d]:%s\n",sdatetime,inet_ntoa(addrclient.sin_addr),addrclient.sin_port,buf);

//如果客戶端傳送「quit」字串,則伺服器退出

if (strcmp(buf, "quit") == 0)

else

else

}break;

}} }

//釋放socket

closesocket(sserver);

closesocket(sclient);

wsacleanup();

system("pause");

return 0;

}

客戶端:

// tcpclient.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include #include #include #pragma comment(lib,"ws2_32.lib")

#define buf_size 64

int _tmain(int argc, _tchar* argv)

//建立socket

shost = socket(af_inet, sock_stream, ipproto_tcp);

if (invalid_socket == shost)

//設定socket為非阻塞模式

int imode = 1;

retval = ioctlsocket(shost, fionbio, (u_long far*)&imode);

if (retval == socket_error)

//設定伺服器socket位址

servaddr.sin_family = af_inet;

servaddr.sin_port = htons(9990);

servaddr.sin_addr.s_un.s_addr = inet_addr("ip位址");//htonl(inaddr_any);

int sserveraddlen = sizeof(servaddr);

//連線到伺服器

while (true)

else if (err == wsaeisconn)

else

}} //收發資料

while (true)

else

}break;

} while (true)

else if (err == wsaetimedout || err == wsaenetdown)

break;

}break;

}printf("recv from server:%s\n",buf);

if (strcmp(buf, "quit") == 0)

}closesocket(shost);

wsacleanup();

system("pause");

return 0;

}

tcp socket阻塞與非阻塞

1.sock預設為阻塞模式,下面的 可對sock設定為非阻塞模式 int flags fcntl sock,f getfl,0 fcntl sock,f setfl,flags o nonblock 假設當前 為伺服器,並且已經執行過如下 當sock為阻塞模式,呼叫accept會阻塞直到乙個請求到來...

socket程式設計 阻塞和非阻塞

阻塞方式下,connect首先傳送syn請求道伺服器,當客戶端收到伺服器返回的syn的確認時,則connect返回.否則的話一直阻塞.非阻塞方式,connect將啟用tcp協議的三次握手,但是connect函式並不等待連線建立好才返回,而是立即返回。返回的錯誤碼為einprogress,表示正在進行...

非阻塞socket程式設計

socket程式設計中可能出現阻塞的呼叫有4個 1.write send sendto sendmsg sendv等,如果某個程序呼叫乙個阻塞的tcp套接字 預設設定 如果傳送緩衝區沒有空間,呼叫程序將會睡眠,直到有空間為止。如果tcp套接字是非阻塞的,且沒有空間可寫,則會返回乙個ewouleblo...