0
我正在寫一個簡單的socket服務器/客戶端。這裏是服務器部分:交流電插座:連接被拒絕[錯誤111]
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
using namespace std;
int main() {
int listenfd;
int connfd;
sockaddr_in servaddr;
char buf[100];
time_t ticks;
if(listenfd = socket(AF_INET,SOCK_STREAM,0) < 0)
cout << "listenfd" << endl;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(10000);
bind(listenfd,(const struct sockaddr*)&servaddr,sizeof(servaddr));
listen(listenfd,5);
for(;;) {
connfd = accept(listenfd,(struct sockaddr *)NULL,NULL);
//cout << "accept link" << endl;
ticks = time(NULL);
snprintf(buf,sizeof(buf),"%.24s\r\n",ctime(&ticks));
//cout << buf << endl;
write(connfd,buf,strlen(buf));
close(connfd);
}
}
這裏是客戶部分:
#include <netinet/in.h>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <arpa/inet.h>
using namespace std;
#define MAX 100
int main(int argc,char **argv) {
int socketfd;
int n;
char buf[MAX+1];
sockaddr_in servaddr;
if(argc !=2)
cout << "stdin error " << endl;
if((socketfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
cout << " socekt error " << endl;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(10000);
if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr) <= 0)
cout << "inet_pton error" << endl;
cout << "prepare linking" << endl;
if(connect(socketfd,(const struct sockaddr*)&servaddr,sizeof(struct sockaddr)) < 0)
{
cout << " connet error" << endl;
cout << strerror(errno);
}
while((n = read(socketfd,buf,MAX)) >0) {
buf[n] = 0;
if(fputs(buf,stdout) == EOF)
cout << "cout error" << endl;
}
if(n < 0)
cout << "read error" << endl;
exit(0);
}
我第一次啓動服務器,並運行像客戶端:./client 127.0.0.1
,但連接與錯誤號111失敗。
我使用Ubuntu 12.04系統。