将python websocket(aiohttp)与androidsocketio库连接起来

2024-05-21 01:07:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经使用AioHttp库在python中创建了一个websocket(非常好用)

此外,我还创建了一个简单的android应用程序,它使用SocketIO库连接到websocket

通过web浏览器连接到websocket时,终端会打印“某人连接到服务器!”每次有人在浏览器中键入ip地址并连接时。下面是我的python代码:

from aiohttp import web
import socketio
import aiohttp_cors

# creates a new Async Socket IO Server
sio = socketio.AsyncServer()
# Creates
app = web.Application()

sio.attach(app)

async def index(request):
    with open('index.html') as f:
        print("Somebody entered the server from the browser!")
        return web.Response(text=f.read(), content_type='text/html')



@sio.on('message')
async def print_message(sid, message):
    # When we receive a new event of type
    # 'message' through a socket.io connection
    # we print the socket ID and the message
    print("Socket ID: " , sid)
    print(message)

# We bind our aiohttp endpoint to our app
# router
cors = aiohttp_cors.setup(app)
app.router.add_get('/', index)

# We kick off our server
if __name__ == '__main__':
    web.run_app(app)

这是我的index.html文件,因此我可以通过web浏览器连接到套接字(工作正常):

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <button onClick="sendMsg()">Hit Me</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script>
      const socket = io("http://142.93.58.172:8080");

      function sendMsg() {
        socket.emit("message", "HELLO WORLDDDDDDDD");
      }
    </script>
  </body>
</html>

在我的android应用程序上,我试着调试,强迫出错以确定问题是否出在服务器端的android端。例如,如果我将应用程序上的url变量更改为“https://...“而不是”http://...,然后连接应用程序,终端中出现错误,表明存在无效的HTTP错误

因此,我认为需要在服务器端“理解”连接来自应用程序,而不是简单的index.html文件

例如,以下是我的android应用程序中的代码:

public class SecondActivity extends AppCompatActivity {
    public static final String CHAT_SERVER_URL = "http://142.93.58.172:8080";
    private Socket mSocket;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            mSocket = IO.socket(CHAT_SERVER_URL);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }

        setContentView(R.layout.activity_second);

        wannaBeChatApplication app = (wannaBeChatApplication) getApplication();
        mSocket = app.getSocket();

        Button startWebSocketBtn = (Button) findViewById(R.id.startWebSocketBtn);
        startWebSocketBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSocket.connect();
                Toast.makeText(SecondActivity.this, "This button got clicked!", Toast.LENGTH_SHORT).show();
                String message = "lol";
                mSocket.connect();
                mSocket.emit("lol", message);
                mSocket.connect();

            }
        });

    }
}

所以问题是,我如何让服务器“理解”连接来自android设备?正如您在代码中所看到的,我尝试以与index.html中相同的方式制作一个按钮,因此当我单击它时,会在终端中打印一些内容,但它不起作用

谢谢


Tags: theiowebapp应用程序httpmessagenew