What's happening when server.accept() - java

I'm trying to write a simple Java chat application in Server/Client.
I'm confusing in below method at server.accept() :
private void waitForConnection() throws IOException {
showMessage("Waiting for someone to connect... \n");
// `connection` is an instance of `java.net.Socket`
// `server` is an instance of `java.net.ServerSocket`
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress().getHostName());
}
Please tell me connection is equal to what?
And also server.accept() returns what?
Any helps would be awesome.

Assuming your server variable is a java.net.ServerSocket then the accept() method returns a java.net.Socket object.
From the returned Socket object, you have access to both the InputStream and OutputStream to read from and write to the connected client.

Your program should halt until a client connects. That's what the line connection = server.accept(); does. Returning type is a type of Socket, too.
That's the "connection" to your client, you can read from and write to.
Check this and that site to read more about network programming in Java.

when you do connections between two systems then you require a socket.
Socket of one system is connected with socket of another system. Both these sockets are connected via I/O stream. you can write to this stream and can read from this stream.
One system serves as server and another system serves as client .
As socket is combination of port no. and IP so server open its port no. and client try to connect with the server's IP and port no.
For connection to be maid the server accepts the incoming socket using accept() function. accept() function returns a local socket which is connected to another socket at the client..
accept() waits until a client socket arrives.

Related

Can ServerSocket write to client before reading from client?

After a ServerSocket accepts a connection to a client, can the ServerSocket start writing data to the client before the client sends a message? When I try to write to the client from the ServerSocket first, the client is blocking forever tyring to read it. However, if have the client send a message to the server first, the I/O streams between them work OK.
The ServerSocket can neither read nor write, but the accepted Socket can do both, in either order, or simultaneously.
Probably you are reading lines but not sending lines, or else not flushing a buffered output stream or writer.
Yes, you are correct that I meant getting the Socket from the accept() method.
My problem was very simple. The client was doing a readLine() method call but the server was not sending the "\n" character.

Multithreaded connections handling

I want to write a server which listens on the given port for connections and puts sockets into BlockingLinkedQueue from which the consumer thread will read messages. I accept incoming connections in this way:
ServerSocket serverSocket = new ServerSocket(port);
while (true)
{
Socket socket = null;
socket = serverSocket.accept();
queue.put(socket);
}
When I try to connect in parallel from two separate hosts it occurs that responses to the first one are sent to the second one after establishing the second connection. When I change my code to this listed below the second connection is merely refused:
while (true)
{
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
queue.put(socket);
}
My questions are:
What's the difference between this two situations? Why in the first situation messages are sent to the second host?
How should I refactor my code in order to create separate connections between my server and both hosts and handle them in parallel?
What's the difference between this two situations?
In the first case, you are using the same port for multiple connections. In the second case, you are discarding the server port so any waiting connections for be refused.
Why in the first situation messages are sent to the second host?
Due to a bug in code, not shown here.
How should I refactor my code in order to create separate connections between my server and both hosts and handle them in parallel?
Create a thread for each connection.

send a string to a specific client on LAN network [duplicate]

I have two wifi modules M1 and M2 that connect to my access point. I have an android phone that connects to the same access point. I have a socket server on my android phone and the two modules join to the server as clients. Now my question is, is it possible to send a string message from my phone to module M1 without having to send anything to M2. I want to choose between clients to send the message to. Is it even possible in Java?
Ok, here goes.
//setting up server
ServerSocket serverSocket = new ServerSocket(8000, 0, IPaddress);
//creating a client socket to accept it
Socket clientSocket = serverSocket.accept();
Now, I accept the client in a seperate thread so that the main thread does not freeze becauz accept() function is blocking.
I don't know how to create a new thread every time a new client connects. Also I dont know how to limit the number of clients that can connect. I need at most 5 clients and no more.
Yes, it is possible. You need to maintain a separate connection to each client. The ServerSocket class has an accept() function which returns a Socket object. That object represents a connection between two points, your server and one client. You can call ServerSocket.accept() multiple times in a loop to accept all incoming connections. Each Socket object returned will be for a different client.
In order to have the server send a message to a specific client, it will need to know which socket belongs to which client, so the clients will have to send some message to the server identifying themselves, and the server will need to read and interpret that message. Then it can respond with the appropriate response for that specific client.
Post your code if you are still having trouble.
UPDATE because you added code to the question: See the Android Documentation about creating threads. That will be a lot of reading beyond this post on stackoverflow.
As to accepting connections and starting threads, just do it in a loop:
for(int i = 0; i<5; i++){
clientSocket = serverSocket.accept();
// start a new thread, passing it the clientSocket as an argument
}
Other possibly useful links:
https://developer.android.com/resources/articles/painless-threading.html
https://developer.android.com/guide/topics/fundamentals/processes-and-threads.html

Something to know about socket and multithreading in java

I want to send a message to a socket on a gateway(client), and then wait for a message to recieve from a gateway.
While waiting, on other hand I again send a message from server socket to gateway which is client but on accept()(ServerSocket) method my connection blocks.
I was wondering is this because of the previous request which was waiting to recieve something by using inputStream. I used threads to maintain this and use setReuseAddress() to do this.
I am not posting a code right now as I just want to know is this logic is fine or is there any logic to handle multiple requests(messages) to be send from a Server-Socket to a client-Socket and I also dont want to close the socket because the socket has to be connected through out the application.
On the client end, you use a Socket object to connect to a server which uses a single ServerSocket. Once the connection is established you will have a Socket at both ends and you can use this Socket to Serversocket connection to send data in either direction. i.e.
A single server socket is needed for new connections only.
See: here

ServerSocket constructor in laymans terms

What would this statement do:
ServerSocket ss=new ServerSocket(4646);
Please explain in layman terms.
The statement effectively tells the JVM to listen on port specified (4646) for incoming connections. By itself it doesn't mean anything since you will have to take incoming connections to that port and use them to build normal Socket objects that will be then used for ingoing/outgoing data.
You could say that the ServerSocket is the object through which real TCP sockets between clients and the server are created. When you create it, the JVM hooks to the operating system telling it to dispatch connections that arrive on that port to your program.
What you typically do is something like:
public AcceptThread extends Thread {
public void run() {
ServerSocket ss = new ServerSocket(4646);
while (true) {
Socket newConnection = ss.accept();
ClientThread thread = new ClientThread(newConnection);
thread.start();
}
}
}
So that you will accept incoming connections and open a thread for them.
Straight from the ServerSocket Java docs:
Creates a server socket, bound to the specified port.
What's a server socket?
This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.
public ServerSocket(int port) throws IOException
documentation:
Creates a server socket, bound to the
specified port. A port of 0 creates a
socket on any free port.
That would bind your ServerSocket to port 4646 on the local machine.
You could then accept sockets on this connection with
// pick up server side of the socket
Socket s = ss.accept();
Now, your client can connect to your server, establishing a socket connection, like this
// pick up client side of the socket, this is in a different program (probably)
Socket connectionToServer = new Socket("myserver",4646);

Categories