基于TCP协议下的Linux网络编程的服务器端和客户端.doc
文本预览下载声明
基于TCP协议下的Linux网络编程的服务器端和客户端
客户端:
Client.c
/*
*************************************************
*Name : Linux Client *
*Date : 2014-11-10 *
*Author : marksman *
*Aim : Linux Client can send and receive *
* message. *
*************************************************
*/
#include stdio.h
#include sys/socket.h
#include netinet/in.h
#include stdlib.h
#include memory.h
#include string.h
int main(int argc,char *argv[])
{
int socketfd,receive_socket;
struct sockaddr_in s_add,c_add;
unsigned short portnum = 0x22B8;
int len;
char buf[100];
/*
*Create the socket
*/
if((socketfd=socket(AF_INET,SOCK_STREAM,0))0)
{
printf(Socket create error! \n);
exit(1);
}
/*
*set the address format
*/
bzero(s_add,sizeof(struct sockaddr_in));
s_add.sin_family = AF_INET;
s_add.sin_addr.s_addr = inet_addr(127.0.0.1);//change the string to 32-bit internet byte.
s_add.sin_port=htons(portnum);
if (connect(socketfd,(struct sockaddr *)(s_add),sizeof(struct sockaddr))0)
{
printf(Connect failure!\n);
return -1;
}
else
printf(Connect Success!\n);
/*
*Using the loop to send and receive the message.
*/
while(1)
{
memset(buf,\0,100);
printf(Input message to send: );
fgets(buf,100,stdin);
len=send(socketfd,buf,strlen(buf)-1,0);
if(len0)
{
printf(send error!\n);
exit(1);
}
else
{
printf(Send Success! send is : %s \n,buf);
}
memset(buf,\0,100);
len=recv(socketfd,buf,100,0);
if(len0)
{
printf(recv error!\n);
exit(1);
}
else if(0 == len)
{
printf(client quit!\n);
exit(1);
}
else
{
printf(receive message is : %s\n,buf);
}
printf(--------------------------\n);
}
close(socketfd);
}
服务器端:
Server.c
/*
*************************************************
*Name : Linux Server *
*Date : 2014-11-10 *
*Author : marksman
显示全部