Why client/server mechanism (using socket's) doesn't work?

不羁岁月 提交于 2019-12-12 01:48:53

问题


I have free account on www.pythonanywhere.com. I have a server written on 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;
     }

Where m_port = 9999 This cod is runed on .pythonanywhere.com server terminal.

And in the main.

    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);*/
.......................

Also, I have a client program in my local pc written on 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()

But the problem is the client can't connect with the server, it waits always. Where is a problem?


回答1:


PythonAnywhere dev here: PythonAnywhere only supports web apps using the Python WSGI protocol, which covers almost all of the main Python web frameworks (Django, web2py, Flask, Bottle, etc) but won't work with your own C-based server.



来源:https://stackoverflow.com/questions/28528086/why-client-server-mechanism-using-sockets-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!