WinC/C++ Socket Server demo
简介:
// WinServer.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.
- // WinServer.cpp : 定义控制台应用程序的入口点。
- //
-
- #include "stdafx.h"
- // 告知编译器,在编译后的链接阶段可以链接“ws2_32.lib”
- #pragma comment(lib,"ws2_32.lib")
-
- #include stdio.h>
- #include WinSock2.h>
- //#include WinSock.h>
- #include stdlib.h>
- #include string.h>
- #include time.h>
- #include stdio.h>
- #include process.h>
- #include Windows.h>
-
- #define TEST_LISTEN_BACKLOG 0//1
- #define SERVER_PORT 4600 // define the defualt connect port id
- #define LENGTH_OF_LISTEN_QUEUE 10//1 // length of listen queue in server
- #define BUFFER_SIZE 255
-
- //void *thread(void *client_fd)
- DWORD WINAPI thread( LPVOID lpParam )
- {
- char buf[BUFFER_SIZE] = {'\0'};
- long timestamp;
-
- time_t rawtime;
- struct tm *timeinfo;
-
- while (1)
- {
- memset(buf, '\0', BUFFER_SIZE);
- if (recv((*(int *)lpParam), buf, BUFFER_SIZE, 0) 0)
- {
- fprintf(stderr, "get message from client error\n");
- closesocket(*(int *)lpParam);
- break;
- }
-
- // Transmission
- Sleep(1000);
- strcat(buf, " : ");
- time(&rawtime);
- timeinfo = localtime(&rawtime);
- strcat(buf,""+timeinfo->tm_sec);
-
- puts(buf);
- send((*(int *)lpParam), buf, strlen(buf), 0);
- }
- return NULL;
- }
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- int server_fd,client_fd;
- struct sockaddr_in servaddr;
- struct sockaddr_in client_addr;
-
- WSADATA wsaD;
- WSAStartup(MAKEWORD(2,2),&wsaD);
- server_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if(server_fd == SOCKET_ERROR)
- {
- printf("new socket error!");
- getchar();
- return -1;
- }
-
- /* two way for init the char array ....
- bzero(&servaddr, sizeof(servaddr)); */
- memset(&servaddr,0,sizeof(servaddr));
-
- servaddr.sin_family = AF_INET;
- servaddr.sin_port = htons(SERVER_PORT);
- servaddr.sin_addr.s_addr = INADDR_ANY; //htons(INADDR_ANY);
-
- int error = 0;
- error = bind(server_fd, (struct sockaddr*)&servaddr, sizeof(servaddr));
- if(error0)
- {
- printf("bind error");
- }
-
-
- listen(server_fd, LENGTH_OF_LISTEN_QUEUE);
-
- #if TEST_LISTEN_BACKLOG
- /* wait the client to connect */
- for (;;)
- {
- printf("server is listening! \n");
- Sleep(1);
- }
- #else
- printf("server is listening! \n");
- #endif
-
- while (1)
- {
- int length = sizeof(client_addr);
- client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &length);
- if(client_fd == -1)
- {
- Sleep(1000);
- continue;
- }
-
- printf("a client connected: IP %s PORT %d\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
-
- Sleep(1000);
- // windows C create thread ....
- if(CreateThread(NULL,0,thread,(void*)&client_fd,0,NULL)==NULL)
- {
- fprintf(stderr, "create thread error\n");
- exit(1);
- }
- }
-
- closesocket(server_fd);
- return 0;
- }