Question

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"

Was it helpful?

Solution

new Thread(new ServerWorker(serverSocket.accept())).start()

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#start%28%29

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top