1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
#include "stdafx.h" #include <stdio.h> #include <winsock2.h> #include <string.h>
#pragma comment(lib,"ws2_32.lib")
typedef struct Books { char title[10]; char name; int int_id[2]; unsigned short int short_id; float book_id; };
int main(int argc, char* argv[]) { 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; }
sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(8888); 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); char revData[255]; while (true) { printf("\n等待连接...\n"); sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen); if (sClient == INVALID_SOCKET) { printf("accept error !"); continue; } printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
struct Books revBook; int ret = recv(sClient, revData, sizeof(Books), 0); if (ret > 0) { for(int i=0;i<sizeof(Books);i++){ printf("%d,",revData[i]); } printf("\n"); memcpy(&revBook, revData, sizeof(revBook)); printf("title:%s\n",revBook.title); printf("name:%c\n",revBook.name); printf("short_id:%d\n",revBook.short_id); printf("int_id[0]:%d\n",revBook.int_id[0]); printf("int_id[1]:%d\n",revBook.int_id[1]); printf("book_id:%f\n",revBook.book_id); } struct Books book; strcpy_s(book.title, "hello-c1"); book.name = 'a'; book.int_id[0] = 253; book.int_id[1] = 13; book.book_id = 22.2; book.short_id = -34;
char snd_buf[sizeof(book)]; memset(snd_buf, 0, sizeof(book)); memcpy(snd_buf, &book, sizeof(book)); printf("\nlen:%d\n",sizeof(book)); printf("\nlen:%d\n",sizeof(snd_buf)); send(sClient, snd_buf, sizeof(snd_buf), 0);
printf("发送:\n"); for(int i=0;i<sizeof(snd_buf);i++){ printf("%d,",snd_buf[i]); }
closesocket(sClient); }
closesocket(slisten); WSACleanup(); return 0; }
|