Update One: Through use of a TCP port checker, I was able to verify that the port 8080 on the AWS instance is active and accepting connections.
This means that the port is likely not being bound properly somehow, will update back if I manage to resolve this issue.
Additionally, through use of the AWS server instance logs, under /var/log/nginx/error.log are entries that suggest the connection is being refused, despite the unrestricted access protocols.
I have a Socket Based Server that runs completely fine on localhost. I start the server, then instance client calls, and behaviour is as desired and expected; the server returns "Hello World" to the client and terminates the connection.
However, if I upload the server to AWS and host it as a Java application, I cannot establish a connection and reproduce the behaviour of the localhost service.
HelloWorldServer:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class NetMiddlewareServer {
public static void main(String[] args) {
// TODO code application logic here
int portNumber = 8080;
while(true){
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()));
) {
System.out.println("Test");
String inputLine, outputLine;
// Initiate conversation with client
outputLine = "Hello World";
out.println(outputLine);
clientSocket.close();
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
HelloWorldClient:
import java.io.*;
import java.net.*;
public class KKPClient {
public static void main(String[] args) throws IOException {
String hostName = "localhost";
int portNumber = 8080;
try (
Socket hwSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(hwSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(hwSocket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
The above code works completely fine locally, however uploading the Server to AWS and changing the hostName leads to errors, and I believe this is where the problem lies.
The IP address for the server instance for example, 52.214.166.199, does not connect and an IOException is thrown when trying to declare the Socket hwSocket. No input is returned as the Socket is not properly created, and so the Hello World message is not received.
Any help is greatly appreciated, thanks.
Stack Trace:
Exception in thread "main" java.net.SocketException: Socket is not connected: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at kkpclient.KKPClient.main(hwClient.java:19)
C:\Users\[me]\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
Related
I have been looking for so long for a way to connect to a server created in Python using java.
Can anyone show me how to connect with java and how to send string? It is recommended that it also works on Android
My server in python:
import socket, time
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.bind(("160.07.08.49", 6784))
soc.listen(5)
(client, (ipNum, portNum)) = soc.accept()
while True:
print(client.recv(1024))
time.sleep(0.5)
My client in Java:
try {
Socket socket = new Socket("160.07.08.49", 6784);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.write("Hello from java");
printWriter.flush();
printWriter.close();
}catch (Exception e) {e.printStackTrace();}
And I got an error from python when the Java client connected
print(soc.recv(20))
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
Python echo server:
import socket
HOST = 'localhost'
PORT = 6784
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Java client:
import java.io.*;
import java.net.Socket;
public class JavaClient {
public static void main(String [] args) {
String serverName = "localhost";
int port = 6784;
try {
Socket client = new Socket(serverName, port);
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The big difference is that I'm doing localhost to localhost. If you need to have the Python server available from outside of localhost, change the bind line to:
soc.bind(("0.0.0.0", 6784))
so that the server will listen on all available interfaces. Then have your Java client connect to the external IP of your server.
I am trying to make connection between a machine(Server) connected to a network(e.g. via hotspot of Network X) and another(Client) connected to hotspot of Network Y.
Issue 1:
The piece of code is working fine if Server and client(can be
multiple) are connected to same Network(say X) but if Server and
client are on different Network(X and Y) then I am getting connection
timeout error.
Issue 2:
If server and client are on same Network(here via router) then also
they are unable to connect with the same above error. I have done port
forwarding(here : 5555) with my router and Firewall and defender put
to Off of both client and server.
What am I missing.Please review !!
Attaching code snippet for Server :
import java.net.*;
import java.io.*;
class ServerSideConnection{
public static void main(String args[]){
try{
while(true){
ServerSocket socket = new ServerSocket(5555);
Socket serverinput = socket.accept();
Mutithrd_excutn mutithrd_excutn_obj = new Mutithrd_excutn(serverinput);
mutithrd_excutn_obj.start();
socket.close();
}
}catch(IOException e){
}
}
}
import java.net.*;
import java.io.*;
class Mutithrd_excutn extends Thread{
public Socket serverinput;
public Mutithrd_excutn(Socket serverinput){
this.serverinput = serverinput;
}
public void run(){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(serverinput.getInputStream()));
PrintWriter pw = new PrintWriter(serverinput.getOutputStream());
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
String str_client = "";
String str_server = "";
while(true){
str_client = br.readLine();
System.out.println("Client : " + str_client);
if(str_client.equals("stop")){
return;
}
str_server = br1.readLine();
pw.println(str_server);
pw.flush();
}
//serverinput.close();
//socket.close();
}catch(IOException e){
}
}
}
Attaching code snippet for Client (here in localhost I am entering
the IP address of Server machine):
import java.io.*;
import java.net.*;
public class ClientSideConnection {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost",5555);
PrintWriter pw = new PrintWriter(s.getOutputStream());
BufferedReader br_client_input = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br_server_output = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str_client = "";
String str_server = "";
while(!str_client.equals("stop")) {
str_client = br_client_input.readLine();
pw.println(str_client);
pw.flush();
if(!str_client.equals("stop")) {
str_server = br_server_output.readLine();
System.out.println("Server : " + str_server);
}
}
br_client_input.close();
br_server_output.close();
s.close();
}catch(IOException e) {
}
}
}
Also,please do write in comment if any point I may have missed n elaborating the problem.
If it is working in the same network but not between different networks then I see the following options:
there is some firewall blocking the connection
or the port forwarding you've setup is done wrong
or you are using the wrong target IP, i.e. the private IP in the target network instead of the public visible IP from the port forwarding
Unfortunately your question does not contain enough details to limit the options further, i.e. it is unknown how the port forwarding is exactly done and which IP address (internal or external) you use as server address in your tests.
How do you code a chat client so that it listens for input both from the server and from the console? This is my current client which successfully sends to and accepts input from the server. As you can see, it doesn't have any code that will enable it to successfully listen for and accept input from the console while also being open to input from the server. The server input would be messages from other chat clients. A message sent from any chat client is broadcast to all other clients. I am pretty new to Java and am completely stuck even though I have a feeling the answer will be depressingly obvious.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientMain
{
public static void main(String[] args) throws UnknownHostException, IOException
{
//DNS of Chat Server
final String HOST = "localhost";
//Port number for chat server connection
final int PORT = 6789;
Socket serverSocket = new Socket(HOST, PORT);
try
{
//Will need three streams for communication: console-client, client-server, server-client
PrintWriter toServer = new PrintWriter(serverSocket.getOutputStream(), true);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
//User must be logged in; any username is acceptable
System.out.print("Enter username > ");
toServer.println("LOGIN " + fromUser.readLine());
String serverResponse = null;
while((serverResponse = fromServer.readLine()) != null)
{
System.out.println("Server: " + serverResponse);
if(serverResponse.equals("LOGOUT"))
{
System.out.println("logged out.");
break;
}
System.out.print("command> ");
toServer.println(fromUser.readLine());
}
toServer.close();
fromServer.close();
fromUser.close();
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
If your main thread is listening to the input from the server, you may start another thread that would keep listening for input from the console. You will have to ensure that you handle input properly. Some flag may be set to indicate if the input is from the server or from the console.
I am writing a program that grabs analog and discrete data points from a PLC (Allen Bradley 1756 L63) via Sockets. So far I am having trouble just creating a socket. My code is as follows:
import java.io.*;
import java.net.*;
class PLCServer
{
public static void main(String argv[]) throws IOException
{
// IP address of the ethernet card
String ENBTIP = "192.168.10.14";
DataInputStream socketReader = null;
PrintStream socketWriter = null;
try
{
Socket client = new Socket(ENBTIP, 9100);
socketReader = new DataInputStream(client.getInputStream());
socketWriter = new PrintStream(client.getOutputStream());
} catch (UnknownHostException e) {
System.out.println("Error setting up socket connection");
System.out.println("host: 192.168.10.14 port: 9100");
} catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
System.out.println("host: 192.168.10.14 port: 9100");
}
// Debugging code
// System.out.println(InetAddress.getByName(ENBTIP).isReachable(10000));
}
}
When I run the program I get a connection refused exception.
Output:
nick#ubuntu:~/Java Programs/PLC Program$ java PLCServer
Error setting up socket connection: java.net.ConnectException: Connection refused
host: 192.168.10.14 port: 9100
Can anyone give me some guidance?
You can try 'ping 192.168.10.14' first, if it has response (and it should be), then try 'telnet 192.168.10.14 9100'. If it has some response like:
Trying 192.168.10.14...
Connected to 192.168.10.14.
Then your java code is somehow wrong. Otherwise it will be the network problem.
I have Developed an Stand alone application (.jar) which is working on Linux environment, I want to Keep this Application on a server(Linux) and want to access through other systems.
Please suggest if this is Possible.
Have you considered Java Webstart ? It'll allow clients to download your application from a webserver and run it locally.
It's traditionally used with GUI (Swing etc.) apps, but I've used it to run daemon and server processes locally.
It'll handle application updates automatically so your clients will only download a version if they'll need it. Otherwise they'll access their locally cached version.
Linux system implements the Berkeley socket API, so yes, you can open communication for the other machines.
For this, you can use package java.net. For socket connection we can use: Socket, ServerSocket, and SocketAddress.
Socket is used for the client, ServerSocket is used to created a socket server, and SocketAddress is used to provide information that will be used as a target socket.
As the illustration, please find the projects below:
First Project SocketServerApp.java - build this and then run java -jar SocketServerApp.jar
package socketserverapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerApp {
public static void main(String[] args) throws IOException {
//we defines all the variables we need
ServerSocket server = null;
Socket client = null;
byte[] receivedBuff = new byte[64];
int receivedMsgSize;
try
{
//activate port 8881 as our socket server
server = new ServerSocket(8881);
System.out.println("Server started");
//receiving connection from client
client = server.accept();
System.out.println("Client connected");
}
catch (IOException e)
{
System.out.println(e.getMessage());
System.exit(-1);
}
//prepare data stream
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
//greet user if there is a client connection
String data;
data = "Hello from the Server!";
out.write(data.getBytes());
//accepting data from client and display it in the console.
java.util.Arrays.fill(receivedBuff, (byte)0);
while (true) {
receivedMsgSize = in.read(receivedBuff);
data = new String(receivedBuff);
//if client type "exit", then exit loop and close everything
if (data.trim().equals("exit"))
{
out.write(data.getBytes());
break;
}
java.util.Arrays.fill(receivedBuff, (byte)0);
System.out.println ("Client: " + data);
}
//close all resources before exiting
out.close();
in.close();
client.close();
server.close();
}
}
Second project is the SocketClientApp.java - build this and then run java -jar SocketClientApp.jar
package socketclientapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClientApp {
public static void main(String[] args) throws IOException {
Socket client = null;
InputStream in = null;
OutputStream out = null;
byte[] receivedMsg = new byte[64];
try {
client = new Socket("localhost", 8881);
in = client.getInputStream();
out = client.getOutputStream();
} catch (UnknownHostException e) {
System.err.println(e.getMessage());
System.exit(1);
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
String fromServer;
String fromUser;
in.read(receivedMsg);
fromServer = new String(receivedMsg);
System.out.println("Server: " + fromServer);
fromUser = "Hello from Client";
System.out.println("Sent to server: " + fromUser);
out.write(fromUser.getBytes());
fromUser = "exit";
out.write(fromUser.getBytes());
System.out.println("Sent to server: " + fromUser);
out.close();
in.close();
client.close();
}
}
Short to say this is a TCP/IP Communication. This type of communication method is very usual in an enterprise that has many kinds of softwares.
Hope that helps.