服务器
#include <stdio.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int sockfd = 0;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
assert(sockfd != -1);
struct sockaddr_in saddr,caddr;
memset(&saddr, 0, sizeof(saddr));
saddr.sin_port = htons(6000);
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
assert(bind(sockfd, (struct sockaddr*)&saddr, sizeof(saddr)) != -1);
listen(sockfd, 1);
socklen_t len = sizeof(caddr);
char buff[1024];
int x = accept(sockfd, (struct sockaddr*)&caddr, &len);
if (x >0) cout<<"ok"<<endl;
while (1)
{
sleep(3);
int i = recv(x, buff ,1024, NULL);
if (i<=0) cout<<"error"<<endl;
cout<<buff<<endl;
}
close(sockfd);
return 0;
}
//客户端
int main()
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in saddr;
memset(&saddr, 0 ,sizeof(sockaddr_in));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
char buff[]="niaho";
int ret = 0;
ret = connect(sockfd, (struct sockaddr*)&saddr, sizeof(saddr));
while (1)
{
for(int i=0; i<10; ++i)
{
int i = send(sockfd, buff, strlen(buff), NULL);
if (i <= 0)cout<<"error";
}
}
close(sockfd);
return 0;
}
tcp是流式套接字,上层所发送的在底层根据情况进行发送。
而udp不会出现这种问题,udp是应用层发送的是什么,底层就将其打包发送,对方收到的和发送者发送的相同。