// winsock.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <io.h> #include <windows.h> #include <winsock.h> #define PORT 8080 int x = 1; void error(char *str) { fprintf(stderr,"%s Error/n",str); exit(1); } DWORD WINAPI new_client_proc(LPVOID lpParam) { SOCKET s = (SOCKET)(lpParam); char p[1024] = "Hi,/n My Client, I'm thread,/n Welcome you"; SYSTEMTIME t; GetSystemTime(&t); sprintf(p,"%4d-%02d-%02d %02d:%02d:%02d.%d", t.wYear, t.wMonth,t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); while( 1 ) { if (x == 1){ x = 0; if(send(s, p, strlen(p), 0) == -1 ) { error("send()"); } printf("Send ok"); break; } Sleep(1); } x = 1; close(s); return 0; } int main(int argc, char* argv[]) { WSADATA WsaData; SOCKET sfd = 0; SOCKET nfd = 0; int len = 0; struct sockaddr_in server; struct sockaddr_in client; HANDLE hThread; DWORD Tid; if (WSAStartup(MAKEWORD(1,1),&WsaData) == -1) { error("WSAStartup()"); } sfd = socket(AF_INET,SOCK_STREAM,0); if (sfd == -1) { error("socket()"); } memset(&server,0,sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sfd,(struct sockaddr *) & server, sizeof(struct sockaddr)) == -1) { error("bind()"); } listen(sfd,5); printf("Now Server is running.../n"); while (1) { len = sizeof(struct sockaddr); nfd = accept(sfd, (struct sockaddr *) &client, &len); //Waiting for Client connecting printf("Client: %s:%d -> /r",inet_ntoa(client.sin_addr), client.sin_port); hThread = CreateThread(NULL, 0, new_client_proc, (LPVOID)nfd, 0, &Tid); if (hThread == NULL) { error("CreateThread()"); } } WSACleanup(); return 0; }