简体   繁体   中英

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:

  • the while(true) continuously passed over those instructions, but creates a Thread only when the accept() method clicks?
  • Does the new thread have a dedicated port? Isn't the socket communication one on one?
  • How does the software keep track of the spawned socket threads, and does it actually matter?
  • How do I send a reply to the thread that just wrote me?

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

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

•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

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