//TCP server
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
int fd;
int fd1;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
fd=socket(AF_INET,SOCK_STREAM,0);
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(5003);
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(fd,(struct sockaddr*)&server_addr,sizeof(struct sockaddr));
listen(fd,10);
while(1)
{
int clientlen=sizeof(client_addr);
fd1=accept(fd,(struct sockaddr*)&client_addr,(socklen_t*)&clientlen);
printf("get the MSG from : %s\n",inet_ntoa(client_addr.sin_addr));
char buf[200];
read(fd1,buf,200);
printf("%s",buf);
write(fd1,"yes you are\n",20);
close(fd1);
}
return 0;
//TCP client
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
int fd;
struct sockaddr_in server_addr;
fd=socket(AF_INET,SOCK_STREAM,0);
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(5003);
server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
connect(fd,(struct sockaddr*)&server_addr,sizeof(struct sockaddr));
write(fd,"Iam the newcomer\n",20);
char buf [200];
read(fd,buf,200);
close(fd);
return 0;
}
PS:
1. write函数有时候会失败(在socket已经断开的情况),此时会有一个异常,貌似还捕获不到。此时有2个解决途径,(1)singal的方法,不过这个方法貌似在MacOSX 或者 IOS上都不行,具体原因不知 (2)在wirte之前使用getsockopt获取一个连接状态,如果确认还是连接状态,就调用write函数。
int optval,optlen = sizeof(int);
getsockopt(_fd,SOL_SOCKET,SO_ERROR,(Char*)&optval,(socklen_t*)&optlen);
if(optval==0)
{
write...
}
else
{
//error
}