Ok, I've done threading with Java before but something that I think should be correct is giving me this error
package com.mdog.tcpserver; import java.net.*; import java.io.*; public class ServerDriver { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; /* bind welcome socket to port */ try { serverSocket = new ServerSocket(1313); } catch (IOException e) { System.err.println("Could not listen on port: 1313."); System.exit(1); } /* assign thread to each client */ while(listening){ new ServerWorker(serverSocket.accept()).start(); } /* close the socket and quit */ serverSocket.close()开发者_如何转开发; return; } }
---------package com.mdog.tcpserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class ServerWorker implements Runnable { private Socket socket = null; public ServerWorker(Socket s){ super(); this.socket = s; } public void run() { (stuff happens) } }
The error is on this line "new ServerWorker(serverSocket.accept()).start();" and it says... "The method start() is undefined for the type ServerWorker"
new Thread(new ServerWorker(serverSocket.accept())).start()
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#start%28%29
Sorry I don't know how to add comments to comments. But
Starting new thread in a while cycle??? This code will crash in a second, I suppose
is wrong. accept() blocks. new threads are created (or would be as the correct answer already given points out) for each new socket (aka connecting client). There's nothing wrong with starting new threads in a while loops vs any other loop as long as it's appropriate which in this case it is.
精彩评论