概述
TCP的读写
有关TCP的socket编程接口的读写如下:
#include<sys/types.h>
#include<sys/socket.h>
ssize_t recv(int sockfd,void buf,size_t len ,int flags);
ssize_t send(int sockfd,const void buf,size_t len,int flags);
recv读取sockfd上的数据,buf和len分别指数据缓冲区的位置和大小。
send向sockfd上写数据,buf和len分别表示数据缓冲区的位置和大小,send成功时返回写入长度的大小
flags参数为数据收发提供了额外的控制,具体参数选择如下图:
以下代码是有关flags参数取 MSG_OOB时的举例:
//fs
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<assert.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
if (argc <= 2)
{
cout<<"usage:"<<basename(argv[0])<<"ip_address port_number"<<endl;
return 1;
}
const char* ip = argv[1];
int port = atoi (argv[2]);
struct sockaddr_in server_address;
bzero(&server_address,sizeof(server_address));
server_address.sin_family = AF_INET;
inet_pton (AF_INET,ip, &server_address.sin_addr);
server_address.sin_port = htons(port);
int sockfd = socket(PF_INET,SOCK_STREAM,0);
assert (sockfd >= 0);
if (connect (sockfd, (struct sockaddr*)&server_address,sizeof(server_address)) < 0)
{
cout<<"connetion failed"<<endl;
}
else
{
const char* oob_data = "simon";
const char* normal_data = "handsome!";
send(sockfd,normal_data, strlen(normal_data),0);
send(sockfd,oob_data,strlen(oob_data),MSG_OOB);
send(sockfd,normal_data,strlen(normal_data),0);
}
close(sockfd);
return 0 ;
}
//js
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<assert.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#define buf 1024
using namespace std;
int main(int argc, char* argv[])
{
if (argc <= 2)
{
cout<<"usage:"<<basename(argv[0])<<"ip_address port_number"<<endl;
return 1;
}
const char* ip = argv[1];
int port = atoi (argv[2]);
struct sockaddr_in address;
bzero(&address,sizeof(address));
address.sin_family = AF_INET;
inet_pton (AF_INET,ip, &address.sin_addr);
address.sin_port = htons(port);
int sockfd = socket(PF_INET,SOCK_STREAM,0);
assert (sockfd >= 0);
int ret = bind(sock,(struct sockaddr*)&address,sizeof(address));
assert(ret != -1);
ret = listen (sock,5);
assert(ret != -1);
struct sockaddr_in client;
sockelen_t client_addrlength = sizeof(client);
int connfd = accept(sock,(struct sockaddr* )&client,&client_addrlength);
if(connfd < 0)
{
cout<<"errno is:"<<errno;
}
else
{
char buffer[buf];
memset(buffer,'