简体   繁体   中英

How do I run my client socket in seperate threads in Java?

I am writing a program to control multiple Pc's over a network switch. I don't know enough about mulithreading to understand how the memory is handled, but how can I call infSockeThread.start(); and have connect to ip1, ip2, ip3..? When I issue my code as is it obviously just overwrites the memory in the InfoSocket class the second time I call it. Basically, I want to run the InfoSocket class as many times as their are PCs, each with their own unique connection to each PC.

For instance, I am calling this in my main class:

        String[] compTestArray = {"172.16.98.6", "172.16.98.3"};

        for(int i = 0; i < compTestArray.length; i++){

            InfoSocket infSocket = new InfoSocket(compTestArray[i]);
            Runnable infRunnable = infSocket;
            Thread infSockeThread = new Thread(infRunnable);

            infSockeThread.start();

        }

And then I have my socket class:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class InfoSocket implements Runnable {

    protected static Socket infoSocket;
    protected static PrintWriter out;
    protected static BufferedReader in;
    protected static String ip;

    public InfoSocket(String ipaddress){

        ip = ipaddress;

    }

    @Override
    public void run() {

        System.out.println("InfoSocket Thread Started");
        // TODO Auto-generated method stub
        String hostName = ip, fromServer = null;
        int portNumber = 6000;
        boolean socketConnected = false;

        while (!socketConnected) {

            try {

                Main.textArea.append("Attempting to connect to " + hostName
                        + "\n");
                Thread.sleep(5000);
                infoSocket = new Socket(hostName, portNumber);
                out = new PrintWriter(infoSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(
                        infoSocket.getInputStream()));

                System.out.println("Connected sent to server");

                // BREAK POINT
                fromServer = in.readLine();

                while (!fromServer.equals("connect")) {

                    Thread.sleep(1000);
                    System.out.print("Waiting for connection response from machine");

                }

                sendResponse(fromServer);

                // Break while loop because connection was successful
                socketConnected = true;

            } catch (Exception e) {
                e.printStackTrace();
                Main.textArea.append("Connection to " + hostName
                        + " failed, trying again\n");
            }
        }

        while (socketConnected) {

            System.out.println("Thread to send response sleeping");

            // Sleep for a second
            try {
                Thread.sleep(300);
                // Get info from server if available
                fromServer = in.readLine();
                System.out.println("From Server: " + fromServer + "\n");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Send response back to server based off
            // of its input, only if the input is not equal to 'null'
            try {
                if (fromServer != null) {

                    System.out.println("Hit sendResponse");
                    sendResponse(fromServer);

                }

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    public static String sendResponse(String action)
            throws InterruptedException, IOException {

        String str = " "; // Value to hold string to be returned

        System.out.println("\nInside sendResponse");
        System.out.println("Inside sendResponse & action is " + action + "\n");

        switch (action) {

        case "connect":
            System.out.println("Inside connect");
            out.println("success");
            break;
        case "ready":
            System.out.println("Inside ready");
            out.println("success");
            break;
        case "sync":
            System.out.println("Inside sync");
            Thread.sleep(10000);
            out.println("success");
            break;
        default:
            out.println(" ");

        }

        System.out.println("end of sendResponse");

        return str;

    }

}

The fields in InfoSocket shouldn't be static . That is why it overwrites the memory the second time you call it. If they were not static , each InfoSocket instance would have its own copy of those variables.

By the way, there is no need to write:

Runnable infRunnable = infSocket;

An InfoSocket is already Runnable . You can simply write:

Thread infSockeThread = new Thread(infSocket);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM