日期:2014-05-16  浏览次数:20824 次

socket问题(跪求答案)
我在写socket时出了一个问题:Transport endpoint is already connected ,请路过的大侠们指教!


我的程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>

int port=12345;
void *server();
int socket_descriptor;//socket描述符

int main()
{
  pthread_t thread_id;
  int sin_len;//字节数
  char message[256];
  struct sockaddr_in serv_addr;//保存socket信息

  int connect_rc,close_rc;
  ssize_t send_rc;
  long save_file_flags;
// printf("Waiting for data from server\n");

//初始化协议族,ip地址,端口号
  bzero(&serv_addr,sizeof((serv_addr))); //清0
  serv_addr.sin_family=AF_INET;//初始化协议族
  serv_addr.sin_addr.s_addr=htons(INADDR_ANY);//初始化IP
  serv_addr.sin_port=htons(port);//初始化端口
  sin_len=sizeof(serv_addr);

//Create a TCP socket and bind it to the port

  socket_descriptor=socket(AF_INET,SOCK_STREAM,0);
  if(socket_descriptor==-1)
  {
  perror("socket call failed");
  exit(errno);
  }
  pthread_create(&thread_id,NULL,&server,NULL);//生成子线程

  usleep(20);
  connect_rc=connect(socket_descriptor,(struct sockaddr *)&serv_addr,sin_len);
  if(connect_rc==-1)
  {
  perror("connect call failed");
  exit(errno);
  }

  while(1)
  {
// sleep(1);
  scanf("%s",message);
  send_rc=send(socket_descriptor,message,sizeof(message),0);
  if(send_rc==-1)
  {
  perror("send call failed");
  exit(errno);
  }
// printf("Response from server:%s\n",message);
  if(strncmp(message,"stop",4)==0)
  {
  printf("Sender has told me to end the connection\n");
  break;
  }
  }
  close_rc=close(socket_descriptor);
  if(close_rc==-1)
  {
  perror("close call failed");
  exit(errno);
  }  
  exit (0);

}

void* server()
{
  int sin_len;
  char message[256];
  struct sockaddr_in my_addr;
  struct sockaddr_in remote_addr;
  int client_fd;
  int bind_rc,close_rc,listen_rc;
  ssize_t recv_rc;
  int BACKLOG=20;
  pthread_t thread_id;
  printf("Wait for data from client\n");

//初始化协议族,ip地址,端口号
  bzero(&(my_addr),sizeof(my_addr));  
  my_addr.sin_family=AF_INET;
  my_addr.sin_addr.s_addr=htons(INADDR_ANY);
  my_addr.sin_port=htons(port);
  sin_len=sizeof(my_addr);

//Create a TCP socket and bind it to the port

#if 0
  socket_descriptor=socket(AF_INET,SOCK_STREAM,0);
  if(socket_descriptor==-1)
  {
  perror("socket call failed");
  exit(errno);
  }
  // pthread_create(thread_id,NULL,&client,NULL);
#endif  
  bind_rc=bind(socket_descriptor,(struct sockaddr *)&my_addr,sizeof(struct so