由于某种原因,我收到错误,57 - 套接字未连接。
为什么?
控制台输出:
GET / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6,lt;q=0.4,nl;q=0.2,ru;q=0.2
Can't write to socket 57
代码:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PORT 8080
#define PROTOCOL 0
#define BACKLOG 10
#define BUFLEN 1500
void str_server(int sock)
{
char buf[1025];
const char* filename = "index.html";
FILE *file = fopen(filename, "rb");
if (!file)
{
printf("Can't open file for reading");
return;
}
while (!feof(file))
{
int rval = fread(buf, 1, sizeof(buf), file);
if (rval < 1)
{
printf("Can't read from file");
fclose(file);
return;
}
int off = 0;
do
{
int sent = send(sock, &buf[off], rval - off, 0);
if (sent < 1)
{
printf("Can't write to socket %d", errno);
fclose(file);
return;
}
off += sent;
}
while (off < rval);
}
fclose(file);
}
int main()
{
int fd;
int connfd;
// For bind()
struct sockaddr_in addr;
// For accept()
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
// For reading and writing
ssize_t i;
ssize_t rcount;
char buffer[BUFLEN];
// Open a socket
fd = socket(AF_INET, SOCK_STREAM, PROTOCOL);
if (fd == -1) {
printf("Error: unable to open a socket\n");
printf("Error code: %d\n", errno);
exit(1);
}
// Create an address
//memset(&addr, 0, sizeof addr);
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
int yes = 1;
if ( setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1 )
{
perror("setsockopt");
}
if ((bind(fd, (struct sockaddr *)&addr, sizeof(addr))) == -1) {
printf("Error: unable to bind\n");
printf("Error code: %d\n", errno);
exit(1);
}
// List for connections
if ((listen(fd, BACKLOG)) == -1) {
printf("Error: unable to listen for connections\n");
printf("Error code: %d\n", errno);
exit(1);
}
// Accept connections
connfd = accept(fd, (struct sockaddr *) &cliaddr, &cliaddrlen);
if (connfd == -1) {
printf("Error: unable to accept connections\n");
printf("Error code: %d\n", errno);
exit(1);
}
// Read data
rcount = read(connfd, buffer, BUFLEN);
if (rcount == -1) {
printf("Error: unable to accept connections\n");
printf("Error code: %d\n", errno);
exit(1);
}
for (i = 0; i < rcount; i++) {
printf("%c", buffer[i]);
}
//write(connfd, buffer, rcount);
str_server(fd);
// Bye
//close(connfd);
return 0;
}
答案 0 :(得分:4)
当您应该发送到已接受/已连接的插座时,您正在发送到侦听套接字。
要修复此传递连接的套接字:
str_server(connfd);