【问题标题】:Processing (multithreading) socket server new serverSocket处理(多线程)socket server new serverSocket
【发布时间】:2013-10-04 16:51:54
【问题描述】:

我正在尝试在处理中创建客户端-服务器通信。 这是 server.pde 的剥离版本:

cThread thread;
ServerSocket socket1;
int main_sid = 0;
int main_port = 5204;

void setup() {
  size(300, 400);
  try {
    ServerSocket socket1 = new ServerSocket(main_port);
  } catch (Exception g) { }
}

void draw() {
  try{
          Socket main_cnn = socket1.accept();
          thread = new cThread(main_cnn,main_sid,20);
          thread.start();
          println("New client: " + main_cnn.getRemoteSocketAddress() + " Assigned sid: " + main_sid);
          main_sid++;

  } catch (Exception g) { }
}

class cThread extends Thread { ...

设置循环应该初始化ServerSocket,并且绘制循环应该尝试不断地接受客户端。

问题是ServerSocket socket1 = new ServerSocket(main_port); 它应该只初始化一次,但在像这样放入设置中时不起作用。

我该怎么办?

【问题讨论】:

    标签: java multithreading sockets client-server processing


    【解决方案1】:

    您声明为字段,然后您在设置中声明为本地...

    如果您声明一个与另一个“全局”/字段具有相同签名的局部变量,就像您所做的那样

    ServerSocket socket1;
    ...
    void setup()
    {
     ...
       ServerSocket socket1... /* here you want to use the socket above...
       but you declare a socket variable with the same signature,
       so to compiler will ignore the field above and will use your local
       variable...
    
       When you try to use the field he will be null because you do not affected
       your state.*/
    

    Java会优先考虑本地的!

    正确的方法:

    void setup()
    {
        size(300, 400);
        try
        {/* now you are using the field socket1 and not a local socket1 */
            socket1 = new ServerSocket(main_port);
        }
       catch (Exception g) { }
    }
    

    【讨论】:

    • 即使“签名”(您的意思是“类型”)不同也会发生。这只是范围问题,而不是“优先级”问题。忽略异常没有什么“正确”的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多