mongona

mongona
-- --
正在获取天气

一个简单的Linux下的socket程序 by C

一个简单的Linux下的socket程序  by C

server ---by  C:

#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
//#include <netinet/in.h>


//int recv(int s, void *buf, int len, unsigned int flags);
// recv() 用于接受socket传来的数据, 并把数据存到有参数buf指定的内存空间, 参数len为接受数据的最大长度
//int recvfrom(int s, void *buf, int len, unsigned int flags, struct )


int main()
{
    // 创建套接字 socket
    int server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    // 绑定ip 端口
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;// IPV4
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // ip
    serv_addr.sin_port = htons(1231);
    bind(server_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    // listen
    listen(server_sock, 20);

    struct sockaddr_in  clnt_addr;
    socklen_t clnt_addr_size = sizeof(clnt_addr);
    printf("wait for connect~~~\n");
    while (1)
    {
        int clnt_sock = accept(server_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
        // recv message
        char buf[1024];
        read(clnt_sock, buf, 1024);
        printf("python: %s\n", buf);
        char str[1024] = "";// = "hello world, this is from C!";
        printf("C:");
        scanf("%c", str);
        write(clnt_sock, str, sizeof(str));
        close(clnt_sock);
    }
   // printf("client addr: %c", clnt_addr)
   // close(clnt_sock);
   // close(server_sock);
    return 0;
}

client---by  python:

from socket import *
import sys
if len(sys.argv) < 2:
    print("error! need port")
    sys.exit(-1)
try:
    port = int(sys.argv[1])
except:
    raise 'error'
while 1:
    clientSocket = socket(AF_INET, SOCK_STREAM)
    clientSocket.connect(("127.0.0.1", port))
    clientSocket.send(input("python:").encode())
    recvData = clientSocket.recv(1024)
    print("C:", end="")
    print("%s"%recvData)
    clientSocket.close()

 

浅尝辄止,  noqa

 

1
0
Tags
富强,民主,文明,和谐,自由,平等,公正,法治,爱国,敬业,诚信,友善。
打赏二维码