Connecting raspberry to java serverSocket - java

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

Related

Java Socket Client not Recieving Data

I have created my first test application implementing a socket server. I am having some issues getting the client to receive data, but the server gets data just fine. Here is the server:
ServerSocket socket = new ServerSocket(11111);
System.out.println("CREATING SERVER...");
while (true) {
Socket SERVER_WORK = socket.accept();
BufferedReader clientIN = new BufferedReader(new InputStreamReader(SERVER_WORK.getInputStream()));
PrintWriter outSend = new PrintWriter(SERVER_WORK.getOutputStream());
String ClientSTR = clientIN.readLine();
System.out.println("Client 1: " + ClientSTR);
String toClient = "Hello";
outSend.write(toClient + '\n');
}
And here is the client:
System.out.println("CONNECTING TO SERVER...");
while (true) {
Socket clientSocket = new Socket(server, 11111);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream toServere = new DataOutputStream(clientSocket.getOutputStream());
Scanner in = new Scanner(System.in);
toServere.write(in.nextLine().getBytes());
if (fromServer.ready())
System.out.println(fromServer.readLine());
clientSocket.close();
}
Everything works properly except for the client receiving data.
I found the solution: I needed a '\n' at the end of the line for the DataOutputStream/PrintWriter for the BufferedReader to work properly.

Java client SocketTimeoutException failed to connect to ip

I am trying to connect my java client made in android studio to a c# host, but I always get this exception.
here is the client code:
{
soc=new Socket();
soc.connect(new InetSocketAddress(ip,port),1000);
DataOutputStream outstream =new DataOutputStream(soc.getOutputStream());
byte[] buffer;
buffer = this.mesaj.getBytes("UTF-8");
outstream.write(buffer);
outstream.flush();
outstream.close();
}
here is the host:
Socket main_soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ip_target = new IPEndPoint(IPAddress.Parse(gen_info.get_ip()), gen_info.get_port());
ascultator.Bind(ip_target);
ascultator.Listen(150);
while (true)
{
Socket transceiver = ascultator.Accept();
if(transceiver.Connected)
{
Thread interpretation_thread = new Thread(() => interpret_signal(transceiver));
interpretation_thread.Start();
}
}
I don't know why this is happening. The host works, when I start it the port appear to be listening in cmd and a c# client on the pc connects with no problem. I used all the ip addresses I found with IP config but none works. I am debugging with an android device(I used 2 actually but none works).

PHP socket Connection refused (Java server)

I have a working Java socket, but I need some help connecting to it with PHP.
My problem: I can connect to the Java socket from a Java client and send/receive messages, but when I try to connect to the same socket with PHP, it won't connect.
This is what I have for the socket in the while loop: (keep in mind this part works)
Socket socket = serverSocket.accept();
System.out.println("Got connection");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String cmd = in.readLine();
System.out.println("Received: " + cmd);
String response = "It worked. Received: " + cmd;
out.println(response);
...
And just to show the other half that works, this is the client:
Socket socket = new Socket("<ip>", port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("test msg");
out.flush();
System.out.println("Sent message");
String r = in.readLine();
System.out.println("Response: " + r);
Now for the part that doesn't work.
This is what I am doing to try and connect with PHP:
$s = fsockopen('<ip>', $port, $errno, $errstr, 25);
if (!$s) {
echo 'Error: '.$errstr;
die;
}
Running that outputs: "Error: Connection refused"
Does anyone know how I can diagnose why the PHP can't connect but the Java client can? They are both accessing the socket externally, and since the Java client can connect it's not blocked. Is there some protocol I forgot to set?
I've looked at dozens of other people with the same question but nobody has provided an answer.
Did you look in the php.ini if fsockopen is allowed ?
1、php.ini, look for line: disable_functions = fsockopen
2、php.ini, see allow_url_fopen = On or allow_url_fopen = Off

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.

Simple Java Chat Program Help, Client Timesout when Connecting With Server

I'm creating a very simple Java chat program, using the Java TCP sockets. I'm new to socket programming and Java. I cannot connect with server, because every time the client connects to server it times out. Maybe, it is because I'm typing the wrong IP address——I don't know.
Here is the code for the Server:
try
{
int fport = Integer.valueOf(port.getText());
ServerSocket server = new ServerSocket(fport);
Socket socket = server.accept();
msg.append("\\n Server is listening to port:" + port.getText());
BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print(msgtxt.getText());
msg.append("\n\n" + input.readLine());
msg.append("\n\n" + Nombre.getText() + msgtxt.getText());
}
catch (Exception ex)
{
msg.setText("\n\n" + "Error:" + ex.getMessage());
}
Here is the code for the Client:
try
{
int iport = Integer.valueOf(port.getText());
int i1;
int i2;
int i3;
int i4;
i1 = Integer.valueOf(ip.getText());
i2 = Integer.valueOf(ip1.getText());
i3 = Integer.valueOf(ip2.getText());
i4 = Integer.valueOf(ip3.getText());
byte[] b = new byte[] {(byte)i1, (byte)i2, (byte)i3, (byte)i4 };
InetAddress ipaddr = InetAddress.getByAddress(b);
Socket sock = new Socket(ipaddr, iport);
BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
output.write(m.getText());
while(!input.ready()){}
msg.setText("\n\n" + input.readLine());
msg.setText("\n\n" + m.getText());
output.close();
input.close();
}
catch (Exception ex)
{
msg.setText("\n\n" + "Error: " + ex.getMessage());
}
verify that you can connect to the server using telnet (on windows you may need to install it as it's not installed by default anymore).
basically, open a connection to your server and see that it works:
telnet host port
if it works, maybe the problem is not in establising the connection but in waiting for a response from the server (add the exception to your question).
one note:
you can open a socket without creating the INetAddress as you did, just new Socket(hostname, port).

Categories