Java Communication Server Client with Socket - java

i'm having trouble with my client/server program in java . I'm able to communicate from my client to my server but when i'm broadcasting from the server to the client it's not working.
There is the part of my program that is not working :
Server :
while (true) {
Socket socket = server.accept();
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome to the server !");
out.flush();
}
Client ( running as a thread):
while(true){
try {
//s is the socket I get from the connection to the server
in = new BufferedReader (new InputStreamReader (s.getInputStream()));
String msg = in.readLine();
System.out.println(msg);
} catch (IOException ex) {
}
}
When I use my client programm I don't receive the message sent by the server . However when i use netcat on my terminal to establish the connection on the server, I got the message . I don't get it. Thanks

The client expects a complete line to be sent:
String msg = in.readLine();
It can only be sure the line is complete if it finds a line terminator character, or if the stream is closed. But the server doesn't send any EOL character, and doesn't close the stream either. So the client keeps waiting for the line to complete.

Related

Java client receiving message from NodeJS server via socket

So basically I'm trying to communicate between a Java client and a NodeJS server. Java sends a message via a socket, Node receives it using an event listener, then Node tries to send a response to Java. Something like "OK" because the message was received.
Java (in Main.java)
try {
Socket s = new Socket("localhost", 6666);
// Send a message to the server
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8);
out.write("test");
out.flush();
// Receive a message from the server
InputStream input = s.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
System.out.println(line);
} catch (Exception e) {
System.out.println(e);
}
NodeJS
var net = require('net');
var server = net.createServer(function (connection) {
console.log("Client connected");
connection.on('data', function (data) {
console.log('Request from', connection.remoteAddress, 'port', connection.remotePort);
console.log(data.toString())
connection.write("OK");
});
})
server.listen(6666, () => console.log(`Server is listening...`));
The server displays:
Server is listening...
Client connected
Request from ::ffff:127.0.0.1 port 65025
test
but the client is empty, it doesn't get server's response.
I can't figue out where the problem is. I found countless examples for two-way socket communications, but most of them between a client/server written both for Java/NodeJS. Their code was still similar with what I wrote, but doesn't work. Thanks a lot!

Socket client not receiving messages from server only when server performs a loop

I am trying to make a server (written in Python) and a client (written in Java) to communicate. The server code is the following:
import socket # Import socket module
connection=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.bind(('',12800))
connection.listen(5)
connection_with_client, info_connection = connection.accept()
msg=b""
while(msg!=b"stop"):
print("Entering loop")
msg = connection_with_client.recv(1024)
connection_with_client.send(b"This is a message")
print("Sent")
connection_with_client.close()
connection.close()
The client code is:
try {
socket = new Socket(InetAddress.getLocalHost(),12800);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print("stop");
out.flush();
System.out.println("Sent");
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message_from_server = in.readLine();
System.out.println("Received message : " + message_from_server);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The strange thing is: when the client sends the message "stop", everything goes fine, message from server is received by the client. Now, when the client sends another message than "stop", the server tells it has sent the message, and enters the loop a second time, however the client never receives the message and gets stuck at the in.readLine() instruction.
I really don't get why as the first passage in the loop should have the same effects in both situations... Any help welcome!
On client side you are using readLine. Obviously, this reads the line, but how it detects where the line ends? The answer is:
you server should append line ending to all messages you send to client.
Try append b'\r\n' or whatever are lineendings on your OS. As far as readLine is called on client side, you should append line ending of a client, not server OS.
For Windows it is b'\r\n'
For Linux b'\n'

Why TCP/IP server with listening port in java not working

I have written a code in java to interface my computer with a transmitter a transmitter device, with a communication board already implemented and ready to connect via TCP/IP to any server with a specific address IP (say 192.168.2.2) and listening to a specific port number (say 4000).
I followed the exact strep how to create a server side application in Java offering a that listening port, so that I can connect to that transmitter.
I don't understand why when I try to debug the code, it blocks a the line clientSocket = serverSocket.accept(), and throws a timeout exception.
Could someone help me find out where the error might be in my code?
Any help would be greatly appreciated.
Thanks.
Here is the code:
public class Server {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Declares server and client socket, as well as the input and the output stream
ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out;
//BufferedReader in;
BufferedReader in;
try{
InetAddress addr = InetAddress.getByName("192.168.2.2");
//Opens a server socket on port 4000
serverSocket = new ServerSocket(4000) ;
//Sets the timeout
serverSocket.setSoTimeout(30000);
System.out.println("Server has connected");
//Create a connection to server
System.out.println("Server listening connection from client ....");
//Listens and waits for client's connection to the server
clientSocket = serverSocket.accept();
// Creates input and output streams to socket
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Reads response from socket
while((in.readLine())!= null ){
System.out.println ( in.readLine() );
}
System.out.println ( "Closing connection ....");
//Terminates connection
clientSocket.close();
serverSocket.close();
System.out.println("Connecton successfully closed");
}
catch(IOException e){
System.out.println(e);
}
}
}
Could someone help me find out where the error might be in my code?
There is no error in your code that could cause this problem. Clearly you haven't configured the device to connect to this server correctly, or the device isn't running, or it isn't connecting, or there is a firewall in the way. Investigate that.
However:
InetAddress addr = InetAddress.getByName("192.168.2.2");
What is this for? It isn't used.
System.out.println("Server has connected");
This is simply not true. The server hasn't connected. At this point all it has done is create a listening socket.
while((in.readLine())!= null ){
Here you are reading a line and throwing it away.
System.out.println ( in.readLine() );
Here you are printing every second line, having thrown every odd line away. The correct way to write this loop is:
String line;
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
Note also that this server will service exactly one client and then exit. There should be a loop around everything from accept() to clientSocket.close(), and if there are multiple devices it should start a new thread per accepted socket to handle the I/O.
You specified timeout of 30 seconds, didn't you? :
serverSocket.setSoTimeout(30000);
So after 30 seconds, no matter whether stopped in debugger or running, this will timeout and throw exception.

Java socket hanging when inside of java servlet

So I've been trying to figure out how to send messages between my arduino and my java servlet (tomcat) and have been bumping into some problems. I'm using this code in my java servlet:
ServerSocket server;
//socket server port on which it will listen
int port = 9876;
String message = "";
//create the socket server object
server = new ServerSocket(port);
System.out.println("Server socket created");
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request...");
//creating socket and waiting for client connection
Socket socket = server.accept();
BufferedReader buff = new BufferedReader(new InputStreamReader (socket.getInputStream()));
System.out.println("Input stream established");
message = buff.readLine();
System.out.println("Message Received: " + message);
buff.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
But it's hanging on the
Socket socket = server.accept();
line. I assume this is because the messages i'm sending from the arduino aren't arriving. On the arduino side of things, this is my client:
if (client.connect(ip, 9876)) {
Serial.println("connected");
client.println("12345678");
Serial.println("Message sent");
} else {
Serial.println("connection failed");
}
Not much to it. Now, I've tried sending this as a HTTP POST request, but without success (surely i'm doing it incorrectly, i just don't know how to do it, i've tried for a while). I know this is probably horrifically written, but i'm very open to learning from you guys today.
The weird thing is that this works exactly how i want it to when i put the java server code in a new regular java project. Can anyone help me figure this out? Why is it hanging in the servlet but not in a regular java project?

TCP connection Socket.getInputStream()

I created an application which establishes connection with the given port and transport data either ways. But I am having issues in reading the data from the server.
try{
Socket skt = new Socket(127.98.68.11, 1111); // connecting to this to get data
String message = "some test message";
if(option.equalsIgnoreCase("send")){
OutputStream outToServer = skt.getOutputStream();
outToServer.write(message); // this is working, message stored on server-side
}else if(option.equalsIgnoreCase("receive")){
BufferedReader in = new BufferedReader (new InputStreamReader(sit.getInputStream()));
String fromServer = in.readLine();
System.Out.Println(fromServer);
}
}catch(IOException io){
io.printStackTrace();
}
In this program everything is working as expected. except in.readline().
I tried running this program in debugging mode, and the by the time compiler reaches this command. is was doing nothing and i can't see the cursor also
It could be because you are trying to do an in.readLine() this requires that the server terminates the "receive" command which it is sending to the client with a newline.. "\n" or "\r\n" along

Categories