Kaj
Kaj

Reputation: 814

multi function socket java, socket vs NIO socket

Take it easy with me, I'm new in socket programming.

I'm about making a program which is similar to Teamviewer. I could make a simple Server/client application which is multithreaded. But the problem is I couldn't figure out how to do something like : Let's say I have Server and a client connected to server. I could transfer a file from client to server. I could make a simple chat with a client. But my problem is : How can I chat with the client while file is transferring in the same time? I mean I couldn't make more than one function in a time.Because we have just one input and one output for both server and client. So how could I send more that one function to client and how could the client read more that one function in a time and respond to requests ? I did something like : I sent a request to client and I got the response in a new thread which contains a new DataInputStream but I couldn't figure out how the main DataInputStream will receive a new response from the client because what is receiving the requests in this way is the new DataInputStream. I'm really lost in this situation because I feel my concept is completely wrong but I couldn't figure out the right concept to do something like that. Is it possible with ServerSocket or should I look at NIO Socket ?

NOTE : I don't want a piece of code, I would like to understand the concept of the whole operation for something like that. Thank you

Upvotes: 0

Views: 71

Answers (1)

Matt Clark
Matt Clark

Reputation: 28629

Use a packet based massaging system over a single connection

Outgoing

{"type":"chat", "message":"hi"}
{"type":"xfer", "fileName":"fileX", "data":"some_binary_data"}

Incoming

switch(getString("type")){

    case "chat":
        System.out.println("User said" + getString("message"));
        break;

    case "xfer":
        File f = new File(getString("fileName"));
        f.write(getString("data"));
        break;

    ...
}

Obviously if the binary file is fairly large, you should break it into many different messages and reassemble it on the other side, this would allow chat messages to make their way across the wire while the transfer is also still taking place.

Upvotes: 1

Related Questions