用户名: 密码: 忘记密码? 注册

linux下Socket编程实例

作者:  时间: 2010-12-02
说明:主要有2个文件:tcp_ser.c和tcp_cli.c
 
/*文件1:tcp_ser.c,服务器*/
#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
//服务器
main()
{
 int lisenfd,connfd;
 struct sockaddr_in ser_addr,cli_addr;
 int cli_len;
 int len = 0;
 char recv_buf[1024];
 char send_buf[1024];
 lisenfd = socket(AF_INET,SOCK_STREAM,0);
 if(-1 == lisenfd)
 {
  perror("Failed to socket");
  return -1;
 }
 memset(&ser_addr,0,sizeof(ser_addr));
 ser_addr.sin_family = AF_INET;
 ser_addr.sin_port = htons(5050);  //这里输入服务器端口号
 ser_addr.sin_addr.s_addr = htonl(INADDR_ANY); //INADDR_ANY表示本机IP
 if(-1 == bind(lisenfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)))
 {
  perror("Failed to bind");
  return -1;
 }
 printf("Now listen...\n");
 if(-1 == listen(lisenfd,10))
 {
  perror("Failed to listen");
  return -2;
 }
 while(1)
 {
  memset(&cli_addr,0,sizeof(cli_addr));
  cli_len = sizeof(cli_addr);
  printf("Now accept...\n");
  connfd = accept(lisenfd,(struct sockaddr *)&cli_addr,&cli_len);
  if(-1 == connfd)
  {
   perror("Failed to accept");
   return -1;
  }
  memset(recv_buf,0,sizeof(recv_buf));
  printf("Now recv...\n");
  len = recv(connfd,recv_buf,sizeof(recv_buf),0);
  if(-1 == len)
  {
   perror("Failed to recv");
   return -1;
  }
  printf("Recv from client is %s\n",recv_buf);
  printf("Now send...\n");
  memset(send_buf,0,sizeof(send_buf));
  sprintf(send_buf,"Hello!client tcp terminal.测试发送");
  len = send(connfd,send_buf,strlen(send_buf),0);
  if(-1 == len)
  {
   perror("Failed to send");
   return -1;
  }
  printf("Send msg to client %s\n",send_buf);
  
  close(connfd);
 }
 close(lisenfd);
 return 0;
}
 
 
/*文件2,tcp_cli.c客户端*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
 int sockfd;
 unsigned short port;
 in_addr_t addr_in;
 struct sockaddr_in ser_addr;
 int len = 0;
 char send_buf[1024];
 char recv_buf[1024];
 
 sockfd = socket(AF_INET,SOCK_STREAM,0);
 if(-1 == sockfd)
 {
  perror("Failed to sockfd");
  return -1;
 }
 
 memset(&ser_addr,0,sizeof(ser_addr));
 ser_addr.sin_family = AF_INET;
 ser_addr.sin_port = htons(5050);
 ser_addr.sin_addr.s_addr = inet_addr("192.168.1.20");
 if(-1 == connect(sockfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)))
 {
  perror("Failed to connect");
  return -1;
 }
 memset(send_buf,0,sizeof(send_buf));
 sprintf(send_buf,"Hello!Server terminal 发送测试");
 len = send(sockfd,send_buf,strlen(send_buf),0);
 if(-1 ==len)
 {
  perror("Failed to send");
  return -1;
 }
 memset(recv_buf,0,sizeof(recv_buf));
 printf("Now recv...\n");
 len = recv(sockfd,recv_buf,sizeof(recv_buf),0);
 if(-1 == len)
 {
  perror("Failed to recv");
  return -1;
 }
 printf("Receive message:%s\n",recv_buf);
 close(sockfd);
 return 0;
}