C Socket
#include "stdafx.h" #include <stdio.h> #include <winsock2.h> #include <string.h> #pragma comment(lib,"ws2_32.lib") extern char* substr(const char*str,unsigned start, unsigned end); extern char * getFirst(char str[]); extern char* getValue(char str[]); extern void writeAfter(char buffer[]); extern void del(char id[]); extern char* searchByID(char id[]); char revData[255]; char sendData[255]; char* responseMsg(char strline[]){ char res[255]; char cmd[255]; char values[255]; strcpy(cmd,getFirst(strline));//cmd就是 add ....这样的命令 strcpy(values,getValue(strline)); printf("server get first is----%s",getFirst(strline)); //当cmd就是add的时候 strcmp的结果是0 所以要加上! 否则不能进入 if(!strcmp(cmd,"add")) { writeAfter(values); strcpy(res,"server get add");//test } else if(!strcmp(cmd,"search")) { strcpy(res,searchByID(values)); } else if(!strcmp(cmd,"del")) { del(values); strcpy(res,"server get del"); } else { strcpy(res,"cmd is not right"); } return res; } int main(int argc, char* argv[]) { //初始化WSA WORD sockVersion = MAKEWORD(2,2); WSADATA wsaData; if(WSAStartup(sockVersion, &wsaData)!=0) { return 0; } //创建套接字 SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(slisten == INVALID_SOCKET) { printf("socket error !"); return 0; } //绑定IP和端口 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(8081); sin.sin_addr.S_un.S_addr = INADDR_ANY; if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("bind error !"); } //开始监听 if(listen(slisten, 5) == SOCKET_ERROR) { printf("listen error !"); return 0; } SOCKET sClient; sockaddr_in remoteAddr; int nAddrlen = sizeof(remoteAddr); printf("等待连接...\n"); sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen); if(sClient == INVALID_SOCKET) { printf("accept error !"); } printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr)); //发送数据 char *sendstr = "Hello Connected\n"; strcpy(sendData,sendstr); send(sClient, sendData, strlen(sendData), 0); int count=1; while(true) { printf("a loop starts count %d ======================\n",++count ); //接收数据 int ret = recv(sClient, revData, 255, 0); if(ret > 0) { revData[ret] = 0x00; printf("server get msg is------%s\n",revData); } //处理revData============================ //发送数据 strcpy(sendData,responseMsg(revData)); strcat(sendData,"\n");//注意java那边使用的是BufferedReader 也就是说要读到一个回车才算是读完一行 否则会一直卡住 printf("Server response is-------%s",sendData); send(sClient, sendData, strlen(sendData), 0); printf("a loop end count %d ======================\n" ,count); } closesocket(sClient); closesocket(slisten); WSACleanup(); char sc=getc(stdin); return 0; }