关于asio socket客户端指定某个端口连接服务器的问题

gimy007 2011-07-04 05:53:36
我想client在连接服务器时,指定某个特定的端口,要怎么写?
...全文
286 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
gimy007 2011-07-05
  • 打赏
  • 举报
回复
揣一个~~~
gimy007 2011-07-05
  • 打赏
  • 举报
回复
顶上去~~~
gimy007 2011-07-05
  • 打赏
  • 举报
回复
恩,可能我的表达没清楚;

服务端的端口是确定的,客户端会随机分配一个端口与服务端端口建立SCOKET连接;

现在的问题是由于防火墙,我客户端的端口只能是某个特定的端口与服务器建立连接。

这是代码

-----------------------------
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(sIP.c_str(), sPort.c_str());
tcp::resolver::iterator endpoint = resolver.resolve(query);
boost::system::error_code error = boost::asio::error::host_not_found;
sock = new tcp::socket(io_service);
sock->connect(*endpoint, error);
-----------------------------------
野男孩 2011-07-04
  • 打赏
  • 举报
回复

//
// blocking_tcp_echo_client.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

enum { max_length = 1024 };

int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
return 1;
}

boost::asio::io_service io_service;

tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
tcp::resolver::iterator iterator = resolver.resolve(query);

tcp::socket s(io_service);
s.connect(*iterator);

using namespace std; // For strlen.
std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = strlen(request);
boost::asio::write(s, boost::asio::buffer(request, request_length));

char reply[max_length];
size_t reply_length = boost::asio::read(s,
boost::asio::buffer(reply, request_length));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}

return 0;
}



boost不是有带example吗?
qq120848369 2011-07-04
  • 打赏
  • 举报
回复
其实关键是绑定分两种,绑定本地端口以便于对方准确访问,以及绑定对端地址,可以省略发送时指定地址..
ouwarmth 2011-07-04
  • 打赏
  • 举报
回复
qq120848369 2011-07-04
  • 打赏
  • 举报
回复
ordinary socket uses "conncect in TCP and connect or sendto in UDP";

gimy007 2011-07-04
  • 打赏
  • 举报
回复
原来是自己随机分配的,所以没指定端口

ok,我去查下
就想叫yoko 2011-07-04
  • 打赏
  • 举报
回复
肯定要指定端口
不指定端口怎么链接
建议你去boost官网下个帮组文档 里面有很多例子

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧