我试图用c ++语言创建一个TCP服务器 - 客户端聊天程序,但是在客户端连接中,connect函数无效,我的连接终止。我尝试过setsockopt方法以及更改端口号但是什么都没有用。请帮帮我!! 这是客户方:
#include <iostream>
#include <bits/stdc++.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
#define IP "10.31.10.157"
int main()
{
int port=80;
int buffersize= 1024;
char buffer[buffersize];
int client,server;
sockaddr_in server_addr;
client=socket(AF_INET,SOCK_STREAM,0);
if(client<0)
{
cout<<"Error creating socket "<<endl;
exit(1);
}
cout<<"Client Socket Created ";
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr= inet_addr(IP);
//server_addr.sin_addr.s_addr= inet_addr(INADDR_ANY);
server_addr.sin_port=htons(port);
if(connect(client,(struct sockaddr *) &server_addr, sizeof(server_addr))>0)
{
cout<<"\nWrite Bye to end connection\n";
while(1)
{
cout<<"Server: ";
recv(client,buffer,buffersize,0);
printf("%s\n",buffer);
cout<<"Client: ";
gets(buffer);
send(client,buffer,buffersize,0);
if(strcmp(buffer,"Bye")==0)
break;
}
}
else
cout<<"Connection Failed";
cout<<"Connection terminated \n";
//close(client);
}
服务器端:
#include <iostream>
#include <bits/stdc++.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main()
{
int server,client;
int buffersize=1024;
char buffer[buffersize];
int portNum=80;
struct sockaddr_in server_addr;
socklen_t size;
client=socket(AF_INET,SOCK_STREAM,0);
if(client<0)
{
cout<<"Error establishing connection "<<endl;
return 0;
}
cout<<"Socket connection established \n";
server_addr.sin_family= AF_INET;
server_addr.sin_addr.s_addr= htons(INADDR_ANY);
server_addr.sin_port= htons(portNum);
if(bind(client, (struct sockaddr *) &server_addr, sizeof(server_addr))<0)
{
cout<<"Error binding socket "<<endl;
return 0;
}
size= sizeof(server_addr);
cout<<"Looking for clients";
listen(client,1);
server= accept(client, (struct sockaddr *)&server_addr, &size);
if(server<0)
{
cout<<"Error on accepting"<<endl;
return 0;
}
if(server>0)
{
cout<<"\nType Bye to end connection\n";
while(1)
{
cout<<"Server: ";
gets(buffer);
send(server,buffer,buffersize,0);
recv(server,buffer,buffersize,0);
cout<<"Client: ";
printf("%s",buffer);
cout<<"\n";
if(strcmp(buffer,"Bye")==0)
break;
}
}
cout<<"Connection terminated ";
//close(client);
}
服务器程序运行正常,但客户端没有连接到服务器!!
答案 0 :(得分:0)
我将分享我正在使用的TCPClient代码。看看你是否可以使用它(直接或修改你的代码);
TCPClient.h
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
class TCPClient
{
private:
static const int DEFAULT_BUFLEN = 512;
static const std::string DEFAULT_PORT;
static const int DEFAULT_TIMEOUT = 2000;
struct addrinfo *result = NULL;
struct addrinfo *ptr = NULL;
struct addrinfo hints;
SOCKET m_connect_socket = INVALID_SOCKET;
public:
TCPClient();
~TCPClient();
bool Connect(const std::string& address, const std::string& port = DEFAULT_PORT);
bool Send(const std::string& data);
bool SetTimeout(int timeout);
std::string Receive();
};
TCPClient.cpp
#include "stdafx.h"
#include "TCPClient.h"
const std::string TCPClient::DEFAULT_PORT = "50015";
TCPClient::TCPClient()
{
}
TCPClient::~TCPClient()
{
closesocket(m_connect_socket);
WSACleanup();
}
bool TCPClient::Connect(const std::string& address, const std::string& port )
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
return false;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(address.c_str(), port.c_str(), &hints, &result) != 0)
{
WSACleanup();
return false;
}
for (ptr = result; ptr != NULL; ptr = ptr->ai_next)
{
m_connect_socket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (m_connect_socket == INVALID_SOCKET)
{
WSACleanup();
return false;
}
if (connect(m_connect_socket, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR) {
closesocket(m_connect_socket);
m_connect_socket = INVALID_SOCKET;
continue;
}
if (!SetTimeout(DEFAULT_TIMEOUT))
{
return false;
}
break;
}
freeaddrinfo(result);
if (m_connect_socket == INVALID_SOCKET)
{
WSACleanup();
return false;
}
return true;
}
bool TCPClient::Send(const std::string& data)
{
return send(m_connect_socket, data.c_str(), data.length(), 0) != SOCKET_ERROR;
}
bool TCPClient::SetTimeout(int timeout)
{
return setsockopt(m_connect_socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout,
sizeof(timeout)) == 0;
}
std::string TCPClient::Receive()
{
char recvbuf[DEFAULT_BUFLEN]="\0";
recv(m_connect_socket, recvbuf, DEFAULT_BUFLEN, 0);
return recvbuf;
}
用法
std::string reply;
std::string message = "message";
TCPClient client;
if (client.Connect("127.0.0.1", "50015")) //check if connection is successful
{
client.SetTimeout(1000); // set the timeout to 1 sec, default timeout=2sec. This line is not necessary
client.Send(message); //send message
reply = client.Receive(); //receive reply
std::cout << "Reply: " << reply << std::endl;
}
else
{
std::cout << "Connection to socket un-successful\n";
}
return 0;
或使用提升http://www.boost.org/doc/libs/1_42_0/doc/html/boost_asio/tutorial/tutdaytime1.html。