SOCKET sock;
SOCKET fd;
uint8* pChunkData;
uint16 chunkLen;
uint16 port = 52428;
void CreateSocket() {
struct sockaddr_in server, client; // creating a socket address structure: structure contains ip address and port number
WORD wVersionRequested;
WSADATA wsaData;
int len;
int iResult;
u_long iMode = 0;
int sockoptval = 1;
printf("Initializing Winsock\n");
wVersionRequested = MAKEWORD (1, 1);
iResult = WSAStartup (wVersionRequested, &wsaData);
if (iResult != NO_ERROR)
printf("Error at WSAStartup()\n");
// create socket
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&sockoptval, 1);
iResult = ioctlsocket(sock, FIONBIO, &iMode);
if (iResult != NO_ERROR)
printf("ioctlsocket failed with error: %ld\n", iResult);
// create socket address of the server
memset(&server, 0, sizeof(server));
// IPv4 - connection
server.sin_family = AF_INET;
// accept connections from any ip adress
server.sin_addr.s_addr = htonl(INADDR_ANY);
// set port
server.sin_port = htons(52428);
//Binding between the socket and ip address
if(bind (sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
printf("Bind failed with error code: %d", WSAGetLastError());
}
//Listen to incoming connections
if(listen(sock, 3) == -1) {
printf("Listen failed with error code: %d", WSAGetLastError());
}
printf("Server has been successfully set up - Waiting for incoming connections");
for(;;) {
len = sizeof(client);
fd = accept(sock, (struct sockaddr*) &client, &len);
if (fd < 0){
printf("Accept failed");
//closesocket(sock);
}
//echo(fd);
printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
}
}
void main() {
HANDLE h1,h2,h3;
int bytes_recieved;
double Task2ms_Raster, Task10ms_Raster, Task100ms_Raster ;
pChunkData = &recv_data;
chunkLen = sizeof(pChunkData);
CreateSocket();
while(1) {
bytes_recieved = recv(fd, recv_data, 100 , 0);
recv_data[bytes_recieved] = '\0';
}
XcpIp_RxCallback (chunkLen, *pChunkData, port);
}
以上是服務器端程序,它正在接受來自主站的連接。我希望打電話給 XcpIp_RxCallback (chunkLen, *pChunkData, port);
的API,只要我在套接字fd
上收到一個數據。誰能告訴我該怎麼做?如何檢查數據到達TCP套接字?
怎麼樣把'如果(bytes_recieved> 0)XcpIp_RxCallback(...);'進入循環? – Marian
它不工作! – user3189297
那麼,你在'CreateSocket'中有另一個無限循環'for(;;)'。它應該如何工作? – Marian