Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 处理(多线程)套接字服务器新服务器套接字_Java_Multithreading_Sockets_Client Server_Processing - Fatal编程技术网

Java 处理(多线程)套接字服务器新服务器套接字

Java 处理(多线程)套接字服务器新服务器套接字,java,multithreading,sockets,client-server,processing,Java,Multithreading,Sockets,Client Server,Processing,我正在尝试在处理中创建客户机-服务器通信。 这是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) { } } vo

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


我该怎么办?

您将声明为字段,然后在安装程序中声明为本地

如果您声明的局部变量与另一个“全局”/字段的签名相同,则

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) { }
}

即使“签名”(您指的是“类型”)不同,也会发生这种情况。这只是一个范围问题,而不是“优先级”问题。忽略异常没有什么“正确”的地方。