C言語記述TCPおよびUDPプロトコルに基づくSocket通信プログラムの例
8924 ワード
Tcp
:
#include
#include
#include
#include
#include
#include
#include
#define PORT 8082
#define BUFSIZE 512
char buf[BUFSIZE+1];
void* fun(void* x)
{
//printf("enter thread!\r
");
int new_fd=*((int*)x);
while(1)
{
int z=read(new_fd,buf,BUFSIZE);// 6
if(z==0){printf("client close !");break;};
buf[z]='\0';
printf("%s\r
",buf);//
};
}
int newfd[512];
int inewfd=0;
int main()
{
// 1
int sockfd=socket(AF_INET,SOCK_STREAM,0);
// 2
struct sockaddr_in svraddr;
svraddr.sin_family=AF_INET;// internet
svraddr.sin_port=htons(PORT);
inet_aton("0.0.0.0",&svraddr.sin_addr);
// 3
int ret=bind(sockfd,(struct sockaddr*)&svraddr,sizeof(svraddr));
if(ret<0){printf("error bind!\r
");exit(-1);};
// 4
listen(sockfd,128);
while(1)
{
newfd[inewfd++]=accept(sockfd,NULL,NULL); // 5
pthread_t ntid;
pthread_create(&ntid,NULL,fun,(void*)&(newfd[inewfd-1]));
}
}
:
gcc server.c -o server -lpthread
cli.c
#include
#include
#include
#include
#include
#include
#include
#define PORT 8082
#define BUFSIZE 512
char
buf[BUFSIZE+1];
int
main()
{
// 1
int
sockfd=socket(AF_INET,SOCK_STREAM,0);
// 2 addr
struct
sockaddr_in svraddr;
svraddr.sin_family=AF_INET;
// internet
svraddr.sin_port=htons(PORT);
inet_aton(
"127.0.0.1"
,&svraddr.sin_addr);
// 3
connect(sockfd,(
struct
sockaddr*)&svraddr,
sizeof
(svraddr));
while
(1)
{
scanf
(
"%s"
,buf);
write(sockfd,buf,
strlen
(buf));
// 4
}
}
Udp
サーバプログラム:#include
#include
#include
#include
#include
#include
#include
#define PORT 8082
#define BUFSIZE 512
char
buf[BUFSIZE+1];
int
main()
{
// 1
int
sockfd=socket(AF_INET,SOCK_DGRAM,0);
// 2
struct
sockaddr_in svraddr;
svraddr.sin_family=AF_INET;
// internet
svraddr.sin_port=htons(PORT);
inet_aton(
"0.0.0.0"
,&svraddr.sin_addr);
// 3
int
ret=bind(sockfd,(
struct
sockaddr*)&svraddr,
sizeof
(svraddr));
if
(ret<0){
printf
(
"cannot bind!\r
"
);
exit
(-1);};
while
(1)
{
struct
sockaddr_in cli;
int
len=
sizeof
(cli);
int
z=recvfrom(sockfd,buf,BUFSIZE,0,(
struct
sockaddr*)&cli,&len);
// 6
buf[z]=
'\0'
;
printf
(
"%s\r
"
,buf);
//
}
}
cli.c
#include
#include
#include
#include
#include
#include
#include
#define PORT 8082
#define BUFSIZE 512
char
buf[BUFSIZE+1];
int
main()
{
// 1
int
sockfd=socket(AF_INET,SOCK_DGRAM,0);
// 2 addr
struct
sockaddr_in svraddr;
svraddr.sin_family=AF_INET;
// internet
svraddr.sin_port=htons(PORT);
inet_aton(
"127.0.0.1"
,&svraddr.sin_addr);
// 3
//connect(sockfd,(struct sockaddr*)&svraddr,sizeof(svraddr));
while
(1)
{
scanf
(
"%s"
,buf);
sendto(sockfd,buf,
strlen
(buf),0,(
struct
sockaddr*)&svraddr,
sizeof
(svraddr));
// 4
}
}