当前位置: 代码迷 >> VC >> Socket代码改错,该如何解决
  详细解决方案

Socket代码改错,该如何解决

热度:6753   发布时间:2013-02-25 00:00:00.0
Socket代码改错
刚弄的daytime协议实现的小程序。但开两个VS用127.0.0.1IP运行客户端一闪就没了,服务器没消失,显示有一个客户端连接了,找不到错,求高手指点啊。附上代码。
服务器:#include "stdafx.h"
#include <stdlib.h>
#include <errno.h>
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib") 
#include <time.h>
#define MAX_BUFFER 1024
#define DAYTIME_SERVER_PORT 13


int main()
{
 int serverFd,connectionFd,i = 1;
 struct sockaddr_in servaddr;
 char timebuffer[MAX_BUFFER + 1];
 time_t currentTime;
 WSADATA wsaData;


 if (WSAStartup( MAKEWORD(2,2), &wsaData ) == SOCKET_ERROR)
 {
  printf("命令套接字初始化失败\n");
  return -1;
 }


 serverFd = socket(AF_INET, SOCK_STREAM,0);


 if(serverFd == -1)
 {
  printf("socket error!\n");
  return(-1);
 }


 memset(&servaddr, 0, sizeof(servaddr));
 servaddr.sin_family = AF_INET;
 servaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
 servaddr.sin_port = htons(DAYTIME_SERVER_PORT);


 bind(serverFd, (struct sockaddr *)&servaddr, sizeof(servaddr));


 listen(serverFd,5);


 while(1)
 {
  connectionFd = accept(serverFd, (struct sockaddr *)NULL, NULL);


  if(connectionFd >=0)
  {
  currentTime = time(NULL);
  sprintf(timebuffer, "%s\n", ctime(&currentTime));
  printf("出现%d个搞不清时间的家伙\n",i++);
  send(connectionFd, timebuffer, strlen(timebuffer),0);
  closesocket(connectionFd);
  }
 }
 return 1;
}

客户端:#include "stdafx.h"
#include <stdlib.h>
#include <errno.h>
#include "winsock2.h"
#include <stdio.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib") 
#define MAX_BUFFER 1024
#define DAYTIME_SERVER_PORT 13


int main(void)
{
 int connectionFd, in;
 struct sockaddr_in servaddr;
 char timebuffer[MAX_BUFFER +1];
 WSADATA wsaData;

 if (WSAStartup( MAKEWORD(2,2), &wsaData ) == SOCKET_ERROR)
 {
  printf("命令套接字初始化失败\n");
  return -1;
 }
 connectionFd = socket(AF_INET,SOCK_STREAM,0);


 if(connectionFd == -1)
 {
  printf("socket error!\n");
  return(-1);
 }


 memset(&servaddr, 0, sizeof(servaddr));
 servaddr.sin_family = AF_INET;
 servaddr.sin_port = htons(DAYTIME_SERVER_PORT);
 
 //inet_addr()把字符串形式的IP地址转换成unsigned long型的整数值
 servaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");


 connect(connectionFd, (struct sockaddr *)&servaddr, sizeof(servaddr));


 while((in = recv(connectionFd, timebuffer, MAX_BUFFER, 0))>0)
 {
  timebuffer[in] =0;
  printf("\n%s",timebuffer);
 }


 closesocket(connectionFd);


 return(0);
}
另外winsock2.h与windows.h头文件包含问题,网上搜到的解决方法是定义宏#define WIN32_LEAN_AND_MEAN。但是我修改之后发现想要实现的在Socket套接字编程客户端发送信息给服务器附带自动发送客户端IP的功能无法实现,在CSDN上搜到的解决方法也大同小异,求指点啊。

------解决方案--------------------------------------------------------
while((in = recv(connectionFd, timebuffer, MAX_BUFFER, 0))>0)
 {
timebuffer[in] =0;
printf("\n%s",timebuffer);
 }

客户端的这个代码根本没用,服务器端发完就立马关闭socket,直接用if就可以。
而且只收发一次,你客户端肯定是收完后就立马结束了
现象没问题。要看你程序输出,加上进程id看两个进程的输出是否正常
  相关解决方案