user-0 提问: socket 通信的问题（errrno 17, File Exists)

回复:
user: user-1
content: 引用 8 楼 zhao4zhong1 的回复:对socket，我只用过recv,没用过read+1

user: user-2
content: 引用 7 楼 biliky 的回复:[quote=引用 6 楼 s120922718 的回复:] 是采用的select吗，select成功以后是要对socket数组遍历的啊 read的时候传递的应该是建立连接的那个socket吧，你的nSockfd是什么  nTcpSelect是一个自定义的函数，该函数里调用了系统的select，这个自定义函数主要就是判断参数中nSockfd是否就绪，是否有数据可读。如果是，则往下执行read，进行读操作。 我的问题是，既然执行到read了，socket应该是有数据可读了，为什么读数据时又报File Exits的错误呢？[/quote]  当recv的参数有些为NULL的时候，recv和read在有些情况下可以理解成是一样的。 传递给read的socket fd是accept成功之后返回的fd，你的nSocketfd是什么

user: user-3
content: 不知道有多少前人掉在TCP Socket send(人多)send(病少)send(财富) recv(人多病)recv(少财富) 陷阱里面啊！ http://bbs.csdn.net/topics/380167545

user: user-4
content: 引用 19 楼 biliky 的回复:好像跟多次读操作有关。客户端连续三次write，服务端也是连续三次read，第一次read正常获得数据，就是第二次read报错。 三次write可能只需要一个read, tcp是流哦。

user: user-5
content: 文件是不是真的存在呢

user: user-0
content: 好像跟多次读操作有关。客户端连续三次write，服务端也是连续三次read，第一次read正常获得数据，就是第二次read报错。

user: user-6
content: c方式，反复设置同一个ip时系统会抛出以下信息 关闭重新连接

user: user-3
content: 参考MSDN98\SAMPLES\VC98\SDK\NETDS\WINSOCK\SIMPLE\IOCTL.C /******************************************************************************\ * ioctl.c - TCP server * *       This is a part of the Microsoft Source Code Samples. *       Copyright 1996-1997 Microsoft Corporation. *       All rights reserved. *       This source code is only intended as a supplement to *       Microsoft Development Tools and/or WinHelp documentation. *       See these sources for detailed information regarding the *       Microsoft samples programs. \******************************************************************************/    #define WIN32_LEAN_AND_MEAN #include <winsock2.h> #include <stdlib.h> #include <stdio.h> #include <string.h>  #define DEFAULT_PORT 5001  int ReadAndEcho(SOCKET , char *,int ) ; int WriteMessage(SOCKET , char *,int ) ;  void Usage(char *progname) {     fprintf(stderr,"Usage\n%s -e [endpoint] -i [interface]\n",         progname);     fprintf(stderr,"Where:\n");     fprintf(stderr,"\tendpoint is the port to listen on\n");     fprintf(stderr,"\tinterface is the ipaddr (in dotted decimal notation)");     fprintf(stderr," to bind to\n");     fprintf(stderr,"Defaults are 5001 and INADDR_ANY\n");     WSACleanup();     exit(1); } int main(int argc, char **argv) {      char Buffer[128];     char *interface= NULL;     unsigned short port=DEFAULT_PORT;     int fromlen;     int i, ioctl_opt =1;     struct sockaddr_in local, from;     WSADATA wsaData;     SOCKET listen_socket, msgsock;     fd_set readfds, writefds, exceptfds;      /* Parse arguments */     if (argc >1) {         for(i=1;i <argc;i++) {             if ( (argv[i][0] == '-') || (argv[i][0] == '/') ) {                 switch(tolower(argv[i][1])) {                     case 'i':                         interface = argv[++i];                         break;                     case 'e':                         port = atoi(argv[++i]);                         break;                     default:                         Usage(argv[0]);                         break;                 }             }             else                 Usage(argv[0]);         }     }          if (WSAStartup(0x202,&wsaData) == SOCKET_ERROR) {         fprintf(stderr,"WSAStartup failed with error %d\n",WSAGetLastError());         WSACleanup();         return -1;     }          if (port == 0){         Usage(argv[0]);     }      //     // The fd sets should be zeroed out before using them to prevent errors.     FD_ZERO(&readfds);     FD_ZERO(&writefds);     FD_ZERO(&exceptfds);     memset(Buffer,0,sizeof(Buffer));      local.sin_family = AF_INET;      //     // bind to specific interface if desired.      local.sin_addr.s_addr = (!interface)?INADDR_ANY:inet_addr(interface);      /*      * Port MUST be in Network Byte Order      */     local.sin_port = htons(port);      listen_socket = socket(AF_INET, SOCK_STREAM,0); // TCP socket     if (listen_socket == INVALID_SOCKET){         fprintf(stderr,"socket() failed with error %d\n",WSAGetLastError());         WSACleanup();         return -1;     }     //     // bind() associates a local address and port combination with the     // socket just created.      if (bind(listen_socket,(struct sockaddr*)&local,sizeof(local) )         == SOCKET_ERROR) {         fprintf(stderr,"bind() failed with error %d\n",WSAGetLastError());         WSACleanup();         return -1;     }      //     // start listening on the socket for incoming connections     //     if (listen(listen_socket,5) == SOCKET_ERROR) {         fprintf(stderr,"listen() failed with error %d\n",WSAGetLastError());         WSACleanup();         return -1;     }     printf("%s: Listening on port %d\n",argv[0],port);      //     // Set the socket to non-blocking mode.     //     if (ioctlsocket(listen_socket,FIONBIO,&ioctl_opt) == SOCKET_ERROR) {         fprintf(stderr,"ioctlsocket failed %d\n",WSAGetLastError());         WSACleanup();         return -1;     }     //     // The structure of the loop below is very simple. We only accept one     // connection at a time. As soon as another client connects, we     // disconnect the first one, and start talking to the new client.     // All this server does is to echo the data received on the socket     // back to the client.     //     // This is not a very realistic server, but it does serve to show that     // select() does not scale very well on win32. If we were dealing     // with more than one client, we would have to have a list of sockets     // that are in each fdset to be able to check them when select()     // returns.     //     while(1) {          //         // A socket in the listen() state becomes ready to read when a         // client connects to it. An accept() will complete without         // blocking.         // Since select sets the sockets that are ready to be read from or         // written to, we have to include listen_socket in the fdset each time         // through the loop.         //          FD_SET(listen_socket,&readfds);          i = select(0,&readfds,&writefds,&exceptfds,NULL);         if (i == SOCKET_ERROR) {             fprintf(stderr,"select failed %d\n",WSAGetLastError());         }         if (i==0){             fprintf(stderr,"Select returned no fds ready\n");         }          if (FD_ISSET(listen_socket, &readfds)){             //             // close the previous client socket.             // We must also clear it from the fdset to prevent select()             // from failing.             // 			closesocket(msgsock); 			FD_CLR(msgsock,&readfds); 			FD_CLR(msgsock,&writefds); 			fromlen = sizeof(from); 			msgsock= accept(listen_socket,(struct sockaddr*)&from,&fromlen); 			if (msgsock == INVALID_SOCKET) { 				fprintf(stderr,"accept failed %d\n",WSAGetLastError()); 				WSACleanup(); 				return -1; 			} 			FD_SET(msgsock,&writefds); 			FD_SET(msgsock,&readfds); 			continue; 		} 		if (FD_ISSET(msgsock,&readfds) ) { 			// 			// socket is ready to read, i.e., there is data on the socket. 			// 			if (ReadAndEcho(msgsock,Buffer,sizeof(Buffer))<0) { 				fprintf(stderr,"terminating connection\n"); 				FD_CLR(msgsock,&readfds); 				FD_CLR(msgsock,&writefds); 				closesocket(msgsock); 				continue; 			} 		} 		if (FD_ISSET(msgsock,&writefds) ){ 			if (WriteMessage(msgsock,Buffer,sizeof(Buffer)) <=0) { 				fprintf(stderr,"terminating connection\n"); 				FD_CLR(msgsock,&readfds); 				FD_CLR(msgsock,&writefds); 				closesocket(msgsock); 				continue;             }         }         FD_SET(msgsock,&writefds);         FD_SET(msgsock,&readfds);     } } int ReadAndEcho(SOCKET insock, char *Buffer,int size) {     int rc;      rc = recv(insock,Buffer,size,0);      if (rc == SOCKET_ERROR) {         fprintf(stderr,"recv() failed with error %d\n",WSAGetLastError());           return -1;     }     if (rc ==0) {         fprintf(stderr,"Connection closed by client\n");         return 0;     }     printf("Received [%s] from client\n",Buffer);     return rc; } int WriteMessage(SOCKET outsock, char *Buffer,int size) {     int rc;     int lasterr;      printf("Sending [%s] to client\n",Buffer);     rc = send(outsock,Buffer,size, 0);      if (rc == SOCKET_ERROR) {       lasterr = WSAGetLastError();       if (lasterr == WSAEWOULDBLOCK)         return 0;       else {         fprintf(stderr,"send() failed with error %d\n",lasterr);             return -1;       }     }     if (rc ==0) {         fprintf(stderr,"Connection closed by client\n");     }     return rc; }

user: user-0
content: 引用 15 楼 mujiok2003 的回复:[quote=引用 12 楼 mujiok2003 的回复:] read不应该返回负数。 返回-1为出错。   nRead的类型是什么？[/quote]  nRead 当然是int类型。     引用 8 楼 zhao4zhong1 的回复:对socket，我只用过recv,没用过read  试过了，用recv效果一样，赵老师，你可是“千万行里改关键源码在弹指瞬间”啊，就等你的弹指瞬间啊。。。。

user: user-7
content: 无码无真相.

user: user-8
content: 引用 2 楼 luciferisnotsatan 的回复:贴代码  read函数能返回一个文件已存在（File Exists）错误？ 修正下 read函数返回失败，errno为17（文件已存在），这有可能么？ read是从文件里面读，怎么会报文件存在这个错误。

user: user-8
content: 贴代码  read函数能返回一个文件已存在（File Exists）错误？

user: user-3
content: 需要用抓包软件排错的话就用。

user: user-4
content: 引用 12 楼 mujiok2003 的回复:read不应该返回负数。 返回-1为出错。   nRead的类型是什么？

user: user-9
content: 试试  unlink

user: user-0
content: 怎么不会返回负数呢？        Upon successful completion, read(), pread(), and readv() return a       non-negative integer indicating the number of bytes actually read.       Otherwise, the functions return -1 and set errno to indicate the       error.

user: user-4
content: read不应该返回负数。

user: user-3
content: 以下内容摘自man 2 recv命令的输出： RETURN VALUE These calls return the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown.    ERRORS These are some standard errors generated by the socket layer. Additional errors may be generated and returned from the underlying protocol modules; see their manual pages.  EAGAIN  The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received.  EBADF  The argument s is an invalid descriptor.  ECONNREFUSED  A remote host refused to allow the network connection (typically because it is not running the requested service).  EFAULT  The receive buffer pointer(s) point outside the process's address space.  EINTR  The receive was interrupted by delivery of a signal before any data were available.  EINVAL  Invalid argument passed.  ENOMEM  Could not allocate memory for recvmsg.  ENOTCONN  The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).  ENOTSOCK  The argument s does not refer to a socket.

user: user-0
content: 在线等各位大牛的高招啊。。。

user: user-0
content: 引用 8 楼 zhao4zhong1 的回复:对socket，我只用过recv,没用过read  赵老师，recv和read有麻区别啊？难道你在用recv中没遇到过File Exists的情况？