Bug when create new Thread for a Socket - java

I'm using this code to constantly accept when a new Socket connect to Server:
while (true) {
Socket socket = null;
socket = ss.accept();
System.out.println("A client is connect...\n");
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Thread acceptClient = new Thread(new ClientHandler(socket, in, out));
acceptClient.start();
}
But when a connection is created, I see this in the console:
A client is connect...
A client is connect...
A client is
connect...
I don't understand why this line is displayed 3 times. Can anyone explane?

Related

Client connects twice when using Postman to send requests?

I'm trying to create a server in Java using Sockets. I create a ServerSocket using ServerSocket serverSocket = new ServerSocket(port); and then attempt to connect using Socket clientSocket = serverSocket.accept();. I send the request through Postman.
My issue is that whenever I send a request, I get the output:
New client connected
input: null
closed!
New client connected
input: PUT / HTTP/1.1
closed!
I'm confused as to why the client connects twice, and why the first request is always empty.
Full code:
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected");
BufferedReader br = new BufferedReader(new InputStreamReader((clientSocket.getInputStream())));
String input = br.readLine();
System.out.println("input: " + input);
clientSocket.close();
System.out.println("closed!");
}

Reading message fails if client not inside a while loop

I have a small TCP server and client where the server is performing inside a while(true) loop meanwhile my client isn't. However when i send a message from the client to the server, the server isn't able to read it. Below is the code and error:
SERVER:
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("[SERVER]: Server launched on port " + port);
while (true) { // the while loop makes the server continuously accept client request
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket);
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println(reader.readLine());
}
CLIENT:
Socket socket = new Socket("localhost", 9101);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("lol");
ERROR:
Exception in thread "main" java.net.SocketException: Connection reset
The error occurs when we try to read data in the server. With all that being said, if i surround the out.println() method in the client in a while(true) loop the error goes away and the code works fine. So i'm wondering why the i get this exception when the server is inside an infinite loop but the client isn't.

Connecting raspberry to java serverSocket

I am trying to make raspberry listen to the java socket server. I run the server code with eclipse and then log in to raspberry desktop and run client.jar. When i run client.jar it does not connect to my server and does not throw any errors. It just 'stays' in the Lxterminal forever and does nothing.
Server
int port = 6666;
Inet4Address add = (Inet4Address) Inet4Address.getLocalHost();
System.err.println(add);
ServerSocket server = new ServerSocket(6666, 1, add);
Socket client = server.accept();
System.err.println("acc");
DataInputStream in = new DataInputStream(client.getInputStream());
DataOutputStream out = new DataOutputStream(client.getOutputStream());
while (true){
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String line = read.readLine();
out.writeUTF(line);
out.flush();
System.err.println(in.readUTF());
}
Client
int port = 6666;
Socket server = new Socket("My ip", port);
DataInputStream in = new DataInputStream(server.getInputStream());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
while (true)
{
String msg = in.readUTF();
if (msg.contentEquals("close"))
server.close();
else if (msg.equals("forward"))
{
out.writeUTF("I go forward master");
out.flush();
}
UPDATE:
I have resolved this problem few seconds ago.My firewall was blocking any connection so the raspberry couldn't connect.
Solution: Go to firewall and network connection and turn it off for private and public connections. I am using Win10

client acting both a as a client and server - JAVA

I have an interesting question. I am trying to establish a peer to peer connection which means a client process acts both as a server and client. Ideally, it should have a client socket (Socket class) and a server socket(Server Socket class). Now I tried to use this concept but it does not work. Please take a look at it:
public static void main(String argv[]) throws Exception
{
Socket clientSocket = null;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Enter the server port u want to be assigned to this peer:");
sentence = inFromUser.readLine();
System.out.println("writing current port to client = "+ sentence);
outToServer.writeBytes("p~"+sentence + "\n" );
int serverport = Integer.parseInt(sentence);
ServerSocket server = new ServerSocket(serverport);
Socket client;
//client
System.out.println("enter port no of the server port of an other peer:");
int msg=Integer.parseInt(inFromUser.readLine());
clientSocket = new Socket("localhost", msg);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("hi");
while(true)
{
//server port listens infinitely and spawns new thread
System.out.println("inside true");
client = server.accept();
Thread serverThread = new Thread(new acceptconnection1(client));
serverThread.start();
}}}
class acceptconnection1 implements Runnable {
BufferedReader inFromClient, inn;
DataOutputStream ds;
Socket socket;
int peersocket;
String clientSentence;
int serverport ;
Socket clientSocket = null;
acceptconnection1 (Socket socket,) throws IOException{
this.socket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new InputStreamReader(socket.getInputStream()));
ds = new DataOutputStream(socket.getOutputStream());
}
#Override
public void run () {
String cs,a;
try {
System.out.println("waiting for connection ");
if(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("Message from other peer" + clientSentence);
}
} catch (IOException ex) {
Logger.getLogger(acceptconnection1.class.getName()).log(Level.SEVERE, null, ex);
}}}
Output:
when I create two client processes,
o/p of client1:
Enter the server port u want to be assigned to this peer:
1111
writing current port to client = 1111
hi enter port no u want to connect to:
2222
inside true
inside true
waiting for connection
Enter the server port u want to be assigned to this peer:
2222
writing current port to client = 2222
hi enter port no u want to connect to:
1111
inside true
inside true
waiting for connection
what happens is both of them wait for connections. how do i solve this?
You have a deadlock condition. To result this, create the ServerSocket first so the Socket has something to talk to. Create the Socket which will connect but do nothing until accepted. Then accept connections.
BTW: You don't need to create two connections for traffic to pass both ways. Once a connection has been established, you can use that one connection as client-server, or server-server or what ever.

Cannot open output stream

For some reasons i have to set up on android SocketServer which waits for connection with computer. All is going good, socket with client (computer) is creating, but streams don't open. It's just pausing without any error or message.
client:
s = new Socket(ip, 4567);
ois = new ObjectInputStream(s.getInputStream());
System.out.println("ois..");// not showing, so can't open input stream
oos = new ObjectOutputStream(s.getOutputStream());
System.out.println("oos.."); // same here
server:
socket = new ServerSocket(4567);
System.out.println("Waiting for connection,,"); // showing
client = socket.accept();
System.out.println("Connected"); //showing
ois = new ObjectInputStream(client.getInputStream());
System.out.println("ois.."); // not showing
oos = new ObjectOutputStream(client.getOutputStream());
System.out.println("oos.."); // not showing too
System.out.println("Stream,s opened");
My apk has INTERNET premissions. I'm using 4567 port. Any other application doesn't block the port.
What can be wrong?
Try opening the ObjectOutputStream first in your server.
socket = new ServerSocket(4567);
System.out.println("Waiting for connection,,"); // showing
client = socket.accept();
System.out.println("Connected"); //showing
oos = new ObjectOutputStream(client.getOutputStream());
ois = new ObjectInputStream(client.getInputStream());
System.out.println("Stream,s opened");
I don't see any timeouts in there, which is why it just stops.
There's probably some network problem; have you verified the IP address of the device is correct?
It's unlikely, but there could be some firewall rule blocking the connection.

Categories