- 论坛徽章:
- 2
|
不知道你要干嘛,没有装*nix,用winsock随手写了一个例子。自己按要求修改吧。是单线程的。- /* rcvstr.c */
- #include <stdio.h>
- #include <winsock2.h>
- #pragma comment(lib, "ws2_32.lib")
- #define PORT 8888
- #define STRING_LEN 32
- struct pdu_struct
- {
- char str[STRING_LEN];
- };
- int output_nstring(const char *s, int len)
- {
- while (*s != '\0' && len-- > 0) {
- putchar(*s++);
- }
- return 0;
- }
- int input_nstring(char *s, int len)
- {
- int c;
- int i;
- for (i = 0; i < len; ++i) {
- if ((c = getchar()) != EOF) {
- if (c == '\n') {
- s[i] = '\0';
- return i;
- }
- s[i] = c;
- continue;
- }
- break;
- }
- while ((c = getchar()) != EOF && c != '\n') {
- }
- return i;
- }
- int main(int argc, const char *argv[])
- {
- struct pdu_struct pdu;
- WSADATA wsadata;
- SOCKET sockfd, sockfd_client;
- struct sockaddr_in addr, addr_client;
- int len;
- if (WSAStartup(MAKEWORD(2, 0), &wsadata) == 0) {
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if (sockfd != INVALID_SOCKET) {
- if (argc == 2 && strcmp(argv[1], "--server") == 0) {
- ZeroMemory(&addr, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_port = htons(PORT);
- if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) != SOCKET_ERROR) {
- if (listen(sockfd, 5) != SOCKET_ERROR) {
- for (;;) {
- len = sizeof(addr_client);
- puts("wait for connection");
- sockfd_client = accept(sockfd, (struct sockaddr *)&addr_client, &len);
- if (sockfd_client != INVALID_SOCKET) {
- printf("connection from %s:%u\n", inet_ntoa(addr_client.sin_addr), ntohs(addr_client.sin_port));
- for (;;) {
- puts("receiving data");
- len = recv(sockfd_client, (char *)&pdu, sizeof(pdu), 0);
- if (len == sizeof(pdu)) {
- output_nstring(pdu.str, STRING_LEN);
- putchar('\n');
- continue;
- }
- break;
- }
- puts("break connection");
- shutdown(sockfd_client, SD_RECEIVE);
- closesocket(sockfd_client);
- continue;
- }
- break;
- }
- closesocket(sockfd);
- WSACleanup();
- return 0;
- }
- }
- }else {
- ZeroMemory(&addr, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_port = htons(PORT);
- addr.sin_addr.s_addr = inet_addr("127.0.0.1");
- if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) != SOCKET_ERROR) {
- printf("Please input string to send to sever. Empty line to exit.\n");
- for (;;) {
- if (input_nstring(pdu.str, STRING_LEN) > 0) {
- if (send(sockfd, (char *)&pdu, sizeof(pdu), 0) == sizeof(pdu)) {
- puts("send ok");
- continue;
- }
- }
- break;
- }
- shutdown(sockfd, SD_SEND);
- closesocket(sockfd);
- WSACleanup();
- return 0;
- }
- }
- closesocket(sockfd);
- }
- WSACleanup();
- }
- return -1;
- }
复制代码 |
|