0

我正在尝试在处理中创建客户端-服务器通信。这是 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); 它应该只初始化一次,但是当把它放在这样的设置中时不起作用。

我应该怎么办?

4

1 回答 1

2

您声明为字段,接下来您在设置中声明为本地...

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

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) { }
}
于 2013-10-04T16:58:23.727 回答