套接字编程(TCP协议)---附代码
程序员文章站
2022-04-29 23:48:04
...
TCP的可靠性:1.应答确认 2.超时重传 3.滑动窗口
//套接字编程:客户端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0); //SOCK_STREAM:流式套接字(TCP)
assert(sockfd != -1);
struct sockaddr_in saddr; //确认链接服务器的信息:
memset(&saddr,0,sizeof(saddr)); //清空
saddr.sin_family = AF_INET; //ipv4地址族
saddr.sin_port = htons(6000); //服务器端口
saddr.sin_addr.s_addr = inet_addr("192.168.31.96"); //此处的ip为服务器的IP地址
int res = connect(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)); //发起链接服务器(三次握手)
assert(res != -1);
while(1)
{
char buff[128] = {0};
printf("input:");
fgets(buff,128,stdin);
if(strncmp(buff,"end",3) == 0)
{
break;
}
send(sockfd,buff,strlen(buff),0);
memset(buff,0,128);
recv(sockfd,buff,127,0);
printf("buff = %s\n",buff);
}
close(sockfd); //服务器recv返回0:
}
//套接字编程:服务器端
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
void *fun(void *arg)
{
int c = (int)arg;
while(1)
{
char buff[128] = {0};
if(recv(c,buff,127,0) <= 0)
{
break;
}
printf("buff(%d) = %s\n",c,buff);
send(c,"ok",2,0);
}
close(c);
}
int main()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0); //ipv4
assert( sockfd != -1 );
struct sockaddr_in saddr,caddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr.s_addr = inet_addr("192.168.31.96");
int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
assert( res != -1);
listen(sockfd,5); //5:已完成三次握手队列长度(测试长度:n+1 = 6),不会超过MAX(128)
while(1)
{
int len = sizeof(caddr);
int c = accept(sockfd,(struct sockaddr*)&caddr,&len);
if(c<0)
{
continue;
}
printf("accept c = %d\n",c);
pthread_t id; //使用多线程,进行多用户同时链接服务端;
pthread_create(&id,NULL,fun,(void *)c); //创建线程
/* while(1)
{
char buff[128] = {0};
if(recv(c,buff,127,0) <= 0) //等待客户端结束
{
break;
}
printf("buff(%d) = %s\n",c,buff);
send(c,"ok",2,0);
}
close(c);
printf("once client end!\n");
*/
}
}
下一篇: ajax异步传送