Vale
Vale

Reputation: 1124

What is happening when we create a new Thread after the socket.accept() method?

I am trying to write a multi-client socket system which communicates via strings sent by the client, which will trigger an event according to its content.
There is a lot of materialon how to do it, but I cannot grasp the logic behind it.
In this example and enter link description here in this one, there is a while true piece of code which has two main instructions:

socket.accept();
Thread t = new Thread(runnable);

I cannot understand how this works:

Maybe it's my lack of google skills, but I cannot find a good tutorial to do this stuff: help?

Upvotes: 0

Views: 528

Answers (2)

ControlAltDel
ControlAltDel

Reputation: 35011

•the while(true) continuously passed over those instructions, but creates a Thread only when the accept() method clicks?

A new Thread is created to listen for data coming in through the Socket (see Socket.getInputStream())

•Does the new thread have a dedicated port? Isn't the socket communication one on one?

Threads do not have ports. But the Socket has a dedicated address for communicating with this client

•How does the software keep track of the spawned socket threads, and does it actually matter?

That depends on the software. But most of the time, you would keep a record of connected Sockets in some sort of Collection - A List perhaps, or a Map between the userID and the Socket if clients are logging in.

•How do I send a reply to the thread that just wrote me?

In a simple sense, it's as simple as

ServerSocket ss = ...;
Socket s = ss.accept();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("Hello World");

You need to make sure that your PrintStream doesn't then get Garbage Collected, as this will close the Stream / Socket

Upvotes: 1

Saulo Aires
Saulo Aires

Reputation: 76

the while(true) continuously passed over those instructions, but creates a Thread only when the accept() method clicks?

the execution stop on method accept() until someone try to connect.You can see this using the debug mode on our IDE.

Does the new thread have a dedicated port? Isn't the socket communication one on one?

No, you have many connections on the same port

How does the software keep track of the spawned socket threads, and does it actually matter?

Do bother about this for now

How do I send a reply to the thread that just wrote me?

When someone try to connect you receive an object to respond this user, check the documentation

Upvotes: 1

Related Questions