linux C TCP資料收發示例

2021-07-30 19:20:30 字數 2621 閱讀 7914

1.client端(讀)

#include #include 

#include

#include

#include

#include

void error_handling(char *msg);

int main(int argc, char *argv)

;

intrcv_len;

if (argc != 3

)

sock_fd = socket(af_inet, sock_stream, 0

);

if (sock_fd == -1

) error_handling(

"sock() error");

memset(&serv_addr, 0, sizeof

(serv_addr));

serv_addr.sin_family =af_inet;

serv_addr.sin_addr.s_addr = inet_addr(argv[1]);//

server's ip addr

serv_addr.sin_port = htons(atoi(argv[2]));//

port

if (connect(sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1

) error_handling(

"connect() error!");

rcv_len = read(sock_fd, message, sizeof(message) - 1

);

if (rcv_len == -1

) error_handling(

"read() error!");

printf(

"message from server: %s\n

", message);

printf(

"read length : %d\n

",rcv_len);

close(sock_fd);

return0;

}void error_handling(char *message)

如果是在client中傳送資料,只需將read修改為write即可。

2.server(傳送)

#include #include 

#include

#include

#include

#include

void error_handling(char *msg);

int main(int argc, char *argv)

serv_sock_fd = socket(af_inet, sock_stream, 0

);

if (serv_sock_fd == -1

) error_handling(

"sock() error");

memset(&serv_addr, 0, sizeof

(serv_addr));

serv_addr.sin_family =af_inet;

serv_addr.sin_addr.s_addr =htonl(inaddr_any);

serv_addr.sin_port = htons(atoi(argv[1

]));

if (bind(serv_sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1

) error_handling(

"bind() error");

if (listen(serv_sock_fd, 5) == -1

) error_handling(

"listen() error");

clnt_addr_size = sizeof

(clnt_addr);

clnt_sock_fd = accept(serv_sock_fd, (struct sockaddr*)&clnt_addr, &clnt_addr_size);

if (clnt_sock_fd == -1

) error_handling(

"accept() error");

write(clnt_sock_fd, message,

sizeof

(message));

close(clnt_sock_fd);

close(serv_sock_fd);

return0;

}void error_handling(char *message)

如果是在server端接收資料,只需將write修改為read即可。

3,以上,在linux下分別gcc編譯,先執行server程式,然後執行client程式,server端等待client的連線,一旦連線並完成資料傳送,server關閉。

4,示例程式的server只能連線乙個client端,並且未進行資料收發的正確性驗證。

Socket收發資料

client write server client read 位元組數writebyte unsignedbyte readunsignedbyte 1 writelengthstring string readstring writebyte byte readbyte 1 writeunsig...

Linux C UDP資料收發

基於udp的通訊時不可靠地,面向無連線的,傳送的資料無法確切知道對方收到沒有,通常用於對可靠性要求不高的通訊中,使用簡單,udp沒有嚴格區分server端和client端,唯一的區別是綁不繫結 bind 埠。1,接收程式 server include include include include ...

socket資料收發

socket讀寫 tcp協議是面向流的,read和write呼叫的返回值往往小於引數指定的位元組數。對於read呼叫,如果接收緩衝區中有20位元組,請求讀100個位元組,就會返回20。對於write呼叫,如果請求寫100個位元組,而傳送緩衝區中只有20個位元組的空閒位置,那麼write會阻塞,直到把...