简体   繁体   English

多个线程写入一台服务器

[英]multiple threads writing to one server

I have a problem. 我有个问题。 I want to create a network connection so that I can make a multiplayer game. 我想创建一个网络连接,以便可以制作多人游戏。 I know and understand sockets. 我知道并了解套接字。 My problem is that if I press two keys on the keyboard at the same time it writes to the socket at the same time which causes an error. 我的问题是,如果我同时按下键盘上的两个键,则会同时将其写入套接字,这会导致错误。 What I then did was create multiple sockets for one client to writ to and only writes to a socket that isn't busy. 然后,我要做的是为一个客户端创建多个套接字以写入,并仅写入不忙的套接字。 By for some reason seems to overload it or something. 由于某种原因,似乎使其过载。 Any ideas for simultaneously sending messages to server and vice versa. 同时向服务器发送消息的任何构想,反之亦然。

Is your code doing like this in server? 您的代码在服务器中是否这样做?

    while (true) {
        try {
            socket = serverSocket.accept();
        } catch (IOException e) {
            System.out.println("I/O error: " + e);
        }
        // new threa for a client
        new MyThread(socket).start();
    }

then, inside MyThread#run 然后,在MyThread#run内部

    inp = socket.getInputStream();
    brinp = new BufferedReader(new InputStreamReader(inp));
    out = new DataOutputStream(socket.getOutputStream());
    line = brinp.readLine(); // read the data.
    out.writeBytes(line + "\n\r"); //write back to client
    out.flush(); // flush socket

Java NIO would faster and efficient. Java NIO将更快,更高效。 Please refer open source netty servers as well. 请同时参考开源Netty服务器。

我已使用一种排队方法,并已解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM