简体   繁体   中英

Multi threading in java socket program

I want to implement multi-threading in my Java socket program. So far I've tried a single connection and it works, but due to being a single connection the process is slow. How should I proceed in order to make the process faster with multi-threading?

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class MRPosting {
    public static String MRPost(String strRequestMessage, String strIP,
            int intPort) throws Exception {
        String strResponseMessage = "";
        try{
        Socket socket = null;
        socket = new Socket(strIP, intPort);
        BufferedInputStream bin = new BufferedInputStream(
                socket.getInputStream());

        PrintWriter pw1 = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())), true);
        pw1.println(strRequestMessage);
        pw1.flush();

        strResponseMessage = readInputStream(bin);
        socket.close();
        socket = null;
        }catch(Exception e){
            strResponseMessage = "ERROR:MRPORT_JAVA:"+e.toString();
            return strResponseMessage;
        }
        return strResponseMessage;  

    }

    public static String readInputStream(BufferedInputStream in)
        throws Exception {
        String read_msg = "";

        int i = in.read();
        if (i == -1) {
            return "-1";
        }
        read_msg = read_msg + (char) i;
        int available = in.available();
        if (available > 0) {
            byte[] Data = new byte[available];
            in.read(Data);
            read_msg = read_msg + new String(Data);
        }
        return read_msg;
    }

}

Multi-threading != increase in speed.

You should read (Google) a lot more about client/server socket programming because yours is not even close to a functioning program. You need a ServerSocket listening on the server and accepting connections from clients, for each connection you will need to open a Socket connection and exchange information through the IO streams.

You won't make this process any faster with multi-threading, unless there are multiple connections, but if there are, just call this stuff from multiple threads with multiple sockets, streams, etc. There's nothing inherently non-thread safe here, as you aren't using any static or instance variables.

NB Get rid of the available() test. It doesn't do what you think. See the Javadoc.

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