Java使代理套接字成为多线程 [英] Java making Proxy Socket multithreaded

查看:94
本文介绍了Java使代理套接字成为多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个Java代理,它可以工作,但只允许1个客户端.我知道我需要进行多线程处理,这就是为什么要这样做,所以它会打开新线程,但是由于某种原因我无法使其正常工作...

I've built a java proxy and it works but only allows 1 client. I know that I need to do multithreading which is why I have done that so it opens new threads but I can't get it to work for some reason...

这是我的代理课程:

public class Proxy {

    private static ServerSocket server;
    private static int port = 9339;
    private static String originalHost = "game.boombeachgame.com";

    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("INFO: Proxy started");
        new Thread(new Runnable() {

            @Override
            public void run() {
                Proxy.startThread();
            }

        }).start();
    }

    public static void startThread() {
        try {
            server = new ServerSocket(port);
            Socket clientSocket = server.accept();
            new Thread(new Server(originalHost)).start();
            new Thread(new Client(clientSocket)).start();
        } catch (Exception e) {
            System.out.println(e);
        }
    }


}

推荐答案

您需要的是一个线程运行一个循环,该循环通过在ServerSocket上调用accept()方法来检查服务器套接字是否有新连接.对于每个连接,您都需要产生一个线程来处理该连接.

What you need is one thread running a loop that checks the server socket for new connections by calling the accept() method on the ServerSocket. For each connection, you need to spawn a thread to handle that connection.

您的代码实际执行的操作是通过一次完全调用一次accept()来检查服务器套接字是否有新连接.然后,您可以正确产生客户端线程来处理该连接.但是,您永远不会再次调用accept().这就是为什么您的代码有效,但仅适用于一个客户端的原因.您还产生了一个服务器"对象的线程.我不确定它是否适合.

What your code actually does is check the server socket for a new connection, by calling accept(), exactly once. You then correctly spawn off a client thread to handle that connection. However, you don't ever call accept() again. This is why your code works, but only for one client. You also spawn off a thread for a "Server" object; I'm not sure how that fits in.

您需要更改的是在循环中运行"server.accept()"语句和关联的线程生成.您还需要确保正确处理线程,以便不同的连接不会最终使用彼此的数据.这可能需要以某种适当的方式连接服务器"对象和客户端"对象.

What you need to change is to run the "server.accept()" statement and associated thread spawning in a loop. You will also need to make sure that you handle the threading correctly so that different connections don't end up using each others' data. This may require hooking up your "Server" objects and your "Client" objects in some appropriate way.

这篇关于Java使代理套接字成为多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆