openSUSE 2.6 X86_64 下测试通过
1 服务器端简化.
-
#include "stdio.h"
-
#include "stdlib.h"
-
#include "string.h"
-
#include "netdb.h"
-
-
int main(int argc, char *argv[])
-
{
-
int servfd, clifd;
-
struct sockaddr_in servaddr, cliaddr;
-
-
if((servfd = socket(AF_INET, SOCK_STREAM,0)) < 0) return;
-
-
bzero(&servaddr, sizeof(servaddr));
-
servaddr.sin_family = AF_INET;
-
servaddr.sin_port = htons(7777);
-
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
-
-
if(bind(servfd, (struct sockaddr*)&servaddr, sizeof(servaddr))<0) return;
-
if(listen(servfd, 24) < 0) return;
-
-
while(1)
-
{
-
socklen_t length = sizeof(cliaddr);
-
if((clifd = accept(servfd, (struct sockaddr*)&cliaddr, &length)) < 0) continue;
-
-
#define BUFFER_SIZE 4096
-
int lenth = 0;
-
char sreceive[BUFFER_SIZE];
-
char ssend[BUFFER_SIZE];
-
-
if((lenth = recv(clifd, sreceive, BUFFER_SIZE,0)) > 0)
-
{
-
printf("[receive]%s\n", sreceive);
-
sprintf(ssend,"hello.\n");
-
send(clifd, ssend, strlen(ssend),0);
-
}
-
-
close(clifd);
-
}
-
-
close(servfd);
-
}
2 客户端简化.
-
char shost[128] = "";
-
char sport[64] = "80";
-
-
//socket
-
struct hostent *host;
-
int portnumber,nbytes;
-
-
if( ( host = gethostbyname( shost)) == NULL) return 0;
-
if( ( portnumber = atoi( sport)) < 0) return 0;
-
-
int sockfd;
-
struct sockaddr_in server_addr;
-
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
-
return 0;
-
-
bzero(&server_addr,sizeof(server_addr));
-
server_addr.sin_family=AF_INET;
-
server_addr.sin_port=htons(portnumber);
-
server_addr.sin_addr=*((struct in_addr *)host->h_addr);
-
-
//select interval
-
struct timeval timeo = {3, 0};
-
socklen_t len = sizeof(timeo);
-
setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeo, len);
-
-
//connect
-
if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)
-
{
-
printf("connect out time.\n");
-
return 0;
-
}
-
-
//send
-
char oRequest[256] = "some thing.";
-
if((nbytes = send( sockfd, oRequest, strlen(oRequest), 0)) == -1)
-
{
-
printf("send out time.\n");
-
return 0;
-
}
-
-
//read
-
char result[10240];
-
char tmp[1024];
-
memset( result, 0x0, sizeof(result));
-
-
int cnt = 0;
-
while( ( nbytes= read( sockfd, tmp, sizeof(result) - 1) ) > 0 )
-
{
-
cnt += nbytes;
-
if( cnt < sizeof(result))
-
strcat( result, tmp);
-
else
-
return 0;
-
}
-
-
printf("[%s]\n", result);
-
close(sockfd);
阅读(1613) | 评论(0) | 转发(1) |