I have been trying to send a simple string between a Java client socket and a Python server socket. This is the code for the server socket:
HOST=''
PORT=12000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADRR,1)
s.bind((HOST,PORT))
s.listen(5)
device=variador()
while True:
conn,addr=s.accept()
if data=="turn_on":
respuesta=device.send_order(variador.start_order)
conn.send(respuesta+'\n')
conn.close()
and the client code is:
try {
Socket socket = new Socket("192.168.10.171", 12000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
out.print(command);
out.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
System.err.println("Unknown Host.");
// System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection.");
// System.exit(1);
}
Everything works fine until I try to read the server's response, using this:
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
then the code hangs and the Python server does not receive any information, which I tested using print.
Is there a problem trying to send first and then wait for a response from the server in the Java client?
Any help will be much appreciated.
Well, I discovered that the Java client hangs because the messages sent by the python server were not explicitly finished with \r\n, so the Python code should have been something like this:
HOST = ''
PORT = 12000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADRR, 1)
s.bind((HOST, PORT))
s.listen(5)
device = variador()
while True:
conn, addr = s.accept()
if data == "turn_on\r\n":
respuesta = device.send_order(variador.start_order)
conn.send(respuesta + '\r\n')
conn.close()
I know it should have been quite obvious from the name of the methods in Java, readline() and println, both suggesting that java ends strings with the sequence \r\n
Connect Python And Java Sockets
Install the package jpysocket
pip install jpysocket
https://pypi.org/project/jpysocket
Import Library jpysocket
The Followings Are The Some Example
Python Server :
import jpysocket
import socket
host='localhost' #Host Name
port=12345 #Port Number
s=socket.socket() #Create Socket
s.bind((host,port)) #Bind Port And Host
s.listen(5) #Socket is Listening
print("Socket Is Listening....")
connection,address=s.accept() #Accept the Connection
print("Connected To ",address)
msgsend=jpysocket.jpyencode("Thank You For Connecting.") #Encript The Msg
connection.send(msgsend) #Send Msg
msgrecv=connection.recv(1024) #Recieve msg
msgrecv=jpysocket.jpydecode(msgrecv) #Decript msg
print("From Client: ",msgrecv)
s.close() #Close connection
print("Connection Closed.")
Java Client :
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try{
Socket soc=new Socket("localhost",12345);
DataOutputStream dout=new DataOutputStream(soc.getOutputStream());
DataInputStream in = new DataInputStream(soc.getInputStream());
String msg=(String)in.readUTF();
System.out.println("Server: "+msg);
dout.writeUTF("Ok Boss");
dout.flush();
dout.close();
soc.close();
}
catch(Exception e)
{
e.printStackTrace();
}}}
Python Client :
import jpysocket
import socket
host='localhost' #Host Name
port=12345 #Port Number
s=socket.socket() #Create Socket
s.connect((host,port)) #Connect to socket
print("Socket Is Connected....")
msgrecv=s.recv(1024) #Recieve msg
msgrecv=jpysocket.jpydecode(msgrecv) #Decript msg
print("From Server: ",msgrecv)
msgsend=jpysocket.jpyencode("Ok Boss.") #Encript The Msg
s.send(msgsend) #Send Msg
s.close() #Close connection
print("Connection Closed.")
Java Server :
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try{
ServerSocket serverSocket = new ServerSocket(12345);
Socket soc = serverSocket.accept();
System.out.println("Receive new connection: " + soc.getInetAddress());
DataOutputStream dout=new DataOutputStream(soc.getOutputStream());
DataInputStream in = new DataInputStream(soc.getInputStream());
dout.writeUTF("Thank You For Connecting.");
String msg=(String)in.readUTF();
System.out.println("Client: "+msg);
dout.flush();
dout.close();
soc.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
If you only want to send a single command on the socket connection, then close the OutputStream after writing the command (using Socket.shutdownOutput()). The socket is reading until EOF and you will not receive EOF until you close the socket. hence, your code never proceeds.
Source - java socket InputStream hangs/blocks on both client and server
Hope it helps!
Related
the question is totally rewritten since I have understood that previously it was really unclear.
I have created a Java Socket server with threads to accept multiple connection in order to handle php tcp requests.
The java server just for the testing purposes it reverse the string supplied from php.
Java server is hosted on a ubuntu server and the php is located on another machine.
The java server shows that php client is connected, but the php is not loading and the string is not sent.
From the codes given below what could be the mistake?
UPDATE
the problem is the received string from the Java server. I have checked with debugger and the BufferedReader is full of '\u0000' and server stops responding. The rest code and communication is working perfect.
How I can avoid those null characters or decode the string correct?
ReverseServer
import java.io.*;
import java.net.*;
public class ReverseServer {
public static void main(String[] args) {
int port = 10007;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");
new ServerThread(socket).start();
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
ServerThread
import java.io.*;
import java.net.*;
public class ServerThread extends Thread {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
String text;
do {
text = reader.readLine();
String reverseText = new StringBuilder(text).reverse().toString();
writer.println("Server: " + reverseText);
} while (!text.equals("bye"));
socket.close();
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
PHP client
<?php
// websocket connection test
$host = "ip_of_server";
$port = 10007;
$message = "Hello";
echo "Message To server :".$message;
$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('TCP'));
$result = socket_connect($socket, $host, $port);
if ($result) {
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server :" . $result;
}
socket_close($socket);
I am trying to read a line, but on the string given on the php client didn't had the carriage return symbol "\r".
Once I have put this on the string it works as expected.
I have written a simple Java TCP Server and a Client (See below).
The idea is quite simple: the Client sends a message to the Server the Server reads it, modify it and sends it back to the client.
import java.io.*;
import java.net.*;
public class ServerTest2 {
public static void main(String[] argv) {
try {
ServerSocket serverSocket = new ServerSocket(2000); // Create Socket and bind to port 2000
System.out.println("Created");
Socket clientSocket = serverSocket.accept(); //Wait for client and if possible accept
System.out.println("Connection accepted");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); // for outputs
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // for inputs
String request; // requst/input of client
String answer; // the answer for the client
System.out.println("Start Waiting");
request = br.readLine(); //Wait for input from client
answer = "answer to "+request;
bw.write(answer); // Send answer to client
System.out.println("send");
bw.newLine();
bw.flush();
//Shut everything down
bw.close();
br.close();
clientSocket.close();
serverSocket.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
The Client Implementation
import java.io.*;
import java.net.*;
public class ClientTest2 {
public static void main(String[] argv) {
try {
String host = "185.75.149.8"; //public ip of router
Socket clientSocket = new Socket(host,2000); //Create and connect Socket to the host on port 2000
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); // for outputs
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // for inputs
String answer;
String request = "HelloWorld";
bw.write(request); //Write to server
bw.newLine();
bw.flush();
System.out.println("Waiting");
answer = br.readLine(); //Wait for answer
System.out.println("Host = "+host);
System.out.println("Echo = "+answer);
//Shut eveything down
bw.close();
br.close();
clientSocket.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
It works perfectly on my local network.
Now I want to use it via the Internet so I installed Port Forwarding on Port 2000 in my Router which sends it to Port 2000 of my PC.
My PC is directly connected to my Router without any Subnets in between.
The Problem is that the Server does not accept the connection(Stops at serverSocket.accept()).
It does not throw an Exception it just waits forever.
The Client does also not throw an Exception (If the Port isn't open it would throw a Connection refused Exception)
This means that the Port Forwarding should work (I have also tested whether the port is open with a Webtool (its open)).
But strangely the Client stops waiting after about 10 seconds and continues with the program.
Since the Port Forwarding should work and my Code works fine in my local Network I absolutely don't know how or where I could find the problem.
I appreciate any help.
Thank you very much!
I'm trying to socket connection between a Ruby Server and a Java Client. The connection is setup with success but I'm finding difficulties when sending a message from server to client.
This is how my Ruby Server looks like:
class ServerSocket
loop do
server = TCPServer.new(ip, port).accept
while server
line = server.recv(65000)
puts "Message: #{line}"
server.flush
server.puts("Hi from server!")
server.flush
end
end
end
When I try with this Java Client:
Socket socket = new Socket(InetAddress.getByName(ip), port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write("Hello from client!");
socket.close();
the connection is established and the message is sent with success from client to server. But when the server reaches this line:
server.puts("Hi from server!")
it throws this exception:
lib/server_socket.rb:11:in `write': Broken pipe (Errno::EPIPE)
from lib/server_socket.rb:11:in `puts'
from lib/server_socket.rb:11:in `block in <class:ServerSocket>'
from lib/server_socket.rb:2:in `loop'
from lib/server_socket.rb:2:in `<class:ServerSocket>'
from lib/server_socket.rb:1:in `<top (required)>'
from /home/dionis/.rvm/gems/ruby-2.4.1#sample/gems/railties-5.1.4/lib/rails/commands/runner/runner_command.rb:34:in `load'
from /home/dionis/.rvm/gems/ruby-2.4.1#sample/gems/railties-5.1.4/lib/rails/commands/runner/runner_command.rb:34:in `perform'
from /home/dionis/.rvm/gems/ruby-2.4.1#sample/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
from /home/dionis/.rvm/gems/ruby-2.4.1#sample/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
from /home/dionis/.rvm/gems/ruby-2.4.1#sample/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
from /home/dionis/.rvm/gems/ruby-2.4.1#sample/gems/railties-5.1.4/lib/rails/command/base.rb:63:in `perform'
from /home/dionis/.rvm/gems/ruby-2.4.1#sample/gems/railties-5.1.4/lib/rails/command.rb:44:in `invoke'
from /home/dionis/.rvm/gems/ruby-2.4.1#sample/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
from bin/rails:9:in `require'
from bin/rails:9:in `<main>'
Another user experience is when I try with this Java Client:
Socket socket = new Socket(InetAddress.getByName(ip), port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write("Hello from client!");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String serverMsg = in.readLine();
System.out.println("Server: " + serverMsg);
socket.close();
Here, I'm trying to get the message from the server. But when the client reaches this line:
String serverMsg = in.readLine();
it just hangs there forever.
Does anyone know how to deal with this?
EDIT (full client code)
ClientSocket.java
public class ClientSocket implements Runnable{
#Override
public void run() {
System.out.println("Connecting...");
try {
Socket socket = new Socket(InetAddress.getByName(ip), port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write("Hello from client!");
socket.close();
System.out.println("Closing...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Main.java
public class Main{
public static void main(String[] args) {
Thread cThread = new Thread(new ClientSocket());
cThread.start();
}
}
#Dionis I am not familiar with java.
Have written a java client and ruby server I guess this will help you.
Ruby TCP server code:
require 'socket'
server = TCPServer.new(12345).accept
line = server.recv(50)
puts "Message from java Client: #{line}"
server.flush
server.puts("Hi from server!")
server.flush
Java TCP Client code:
import java.net.*;
import java.io.*;
class Main{
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 12345);
DataInputStream is = new DataInputStream(socket.getInputStream());
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
os.writeBytes("Hello \n");
String line = is.readLine();
System.out.println("Msg from ruby Server :" + line);
socket.close();
}
}
Let me know if resolve the issue
Thanks!
Hello programmers on the internet. I am currently stepping through an operating systems book and there are some exercises that involve the following pieces of code.
This is the server code
import java.net.*;
import java.io.*;
public class DateServer{
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true) {
Socket client = sock.accept();
PrintWriter pout = new
PrintWriter(client.getOutputStream(), true);
// write the Date to the socket
pout.println(new java.util.Date().toString());
// close the socket and resume
// listening for connections
client.close();
}
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
This is the client code
import java.net.*;
import java.io.*;
public class DateClient{
public static void main(String[] args) {
try {
//make connection to server socket
Socket sock = new Socket("127.0.0.1",6013);
InputStream in = sock.getInputStream();
BufferedReader bin = new
BufferedReader(new InputStreamReader(in));
// read the date from the socket
String line;
while ( (line = bin.readLine()) != null)
System.out.println(line);
// close the socket connection
sock.close();
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}
So to my understanding the server is creating a socket and writing a date value to it. The client is then coming a long and connecting to the server and writing out the value in that socket. Am I interpreting this code correctly? This is my first experience with sockets.
Now for my actual question. I want to have the client connect to the server (and print out a message saying you are connected) and then be able to send a value over to the server so that the server can process it. How would I go about doing this? I have tried tinkering with DataOutputStream and DataInputStream but I have never used either before. Any help would be GREATLY appreciated.
You are correct. You have the server writing to the socket and the client reading from the socket. You want to reverse that.
Server Should look like:
ServerSocket sock = new ServerSocket(6013);
// now listen for connections
while (true)
{
Socket client = sock.accept();
InputStream in = client.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
// read the date from the client socket
String line;
while ((line = bin.readLine()) != null)
System.out.println(line);
// close the socket connection
client.close();
}
The client should look like:
try
{
// make connection to server socket
Socket sock = new Socket("127.0.0.1", 6013);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
// send a date to the server
out.println("1985");
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}
I am trying to connect a client application to my code through port 8000 on my pc offline. I am using the ServerSocket library to connect using the below code. The client's application sends XML messages across the port and I need to connect, interpret and respond. (Please bear in mind that I haven't coded interpret/respond yet when reading the below).
Every time I try to send a message from the client application (when running the debug feature in eclipse), the code gets to the serverSocket.accept() method which should be the 'handshake' between client and server and can't go any further. I am unable to change the client application obviously so need to figure out why it's not accepting the connection.
package connect;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class PortListener2 {
public static void main(String[] args){
System.out.println("> Start");
int portNumber = 8000;
try (
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: "+inputLine);
out.println(inputLine);
if (inputLine.equals("exit")){
break;
}
}
} catch (Exception e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println("Disconnected");
}
}
}