为什么客户端/服务器机制(使用套接字)不起作用?
Why client/server mechanism (using socket's) doesn't work?
我在www.pythonnywhere.com上有一个免费帐户。我有一个用c++编写的服务器
some_space::socket_server::socket_server(unsigned int port):
m_port(port),
m_tcp_fd(0),
m_udp_fd(0),
m_newfd(0)
{
m_addr.sin_family = AF_INET;
m_addr.sin_addr.s_addr = htonl(INADDR_ANY);
m_addr.sin_port = htons(m_port);
}
void some_space::socket_server::set_port(unsigned int port)
{
assert(port != 0);
m_port = port;
}
int some_space::socket_server::create_tcp_connection()
{
m_tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
if(m_tcp_fd < 0) {
perror("Error: Cannot set up the communication");
return -1;
}
int status = bind(m_tcp_fd, (struct sockaddr *)&m_addr, sizeof(m_addr)); if(status < 0) {
perror("Error: Cannot set up the communication");
return -1;
}
status = listen(m_tcp_fd, 5);
if(status == 0) {
m_newfd = accept(m_tcp_fd, (struct sockaddr*)NULL, NULL);// ####################### The code freezes here (on the accept)
if(m_newfd != -1) {
return m_newfd;
}
perror("Error: Cannot accept the connection");
return -1;
}
perror("Error: The port cannot be listened");
return -1;
}
其中m_port = 9999
此cod在.pythonanywhere.com服务器终端上运行。
总的来说。
some_space::socket_server* s = new some_space::socket_server(9999);
assert(s != 0);
int r = s->create_tcp_connection(); // it it freezes in this function
assert(r != -1);
std::string rsp("");
s->recv_response(rsp);
std::string rec("some data");
const char* t = rec.c_str();
char* buf = const_cast<char*>(t);
int size = rec.length();
r = s->send_data(buf, size);
assert(r != -1);*/
.......................
此外,我在本地电脑上有一个用python编写的客户端程序。
#!/usr/bin/env python
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('<username>.pythonanywhere.com', 9999))
sock.send('hello, world!')
data = sock.recv(1024)
print "receive >>> %s" % data
sock.close()
但问题是客户端无法连接到服务器,它总是在等待。哪里有问题?
PythonAnywhere在这里开发:PythonAAnywhere只支持使用Python WSGI协议的web应用程序,该协议几乎涵盖了所有主要的Python web框架(Django、web2py、Flask、Bottle等),但不能与您自己的基于C的服务器一起工作。
相关文章:
- 嵌套While循环不起作用(C++问题)
- Opencv 链接 CMAKE 不起作用 Ubuntu 16.04 Docker
- 为什么此代码用于单个链接列表不起作用
- 套接字不async_read
- 使用引用遍历链接列表不起作用
- 套接字不起作用,当添加 opencv libriary
- 为什么嵌套如果语句不起作用
- C++套接字不能接收超过 21845 字节
- 基于双重链接列表不起作用的Deque实施
- 为什么UDP套接字不关闭原因选择要返回
- 为什么客户端/服务器机制(使用套接字)不起作用?
- 套接字不命名类型
- 套接字不能用作函数
- 如果客户端的互联网断开连接,客户端套接字不会关闭。如何在服务器中检测此事件?
- 套接字不接受连接
- 为什么这个嵌套开关语句不起作用?(C++)
- 如何使多播套接字不接收单播数据?
- 没有多线程的c++套接字不同步/并行代码
- QT QUdp套接字不发送/接收数据
- 写入TCP套接字不完整c++