Java client SocketTimeoutException failed to connect to ip - java

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).

Related

What is protocol I can use for connection?

What is port I can use for someone can connect me and get message connection is established ?
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"),true);
printWriter.println("Connection is established");
Thank you
Welcome to SO Deny
The port is for you (the server) to decide.
The client needs to know what port to connect to, so it can get a response.
For your question, just don't pick some port that currently your computer is using will be fine. Such as like 20 or 80, those ports are using in real http data transferring
In the below codes, your can notice that I just randomly pick a port, to note that, both ports in sender and receiver have to be the same, otherwise, you will not get the message.
This one is TCPSender.py
from socket import *
serverName = 'localhost'
serverPort = 8797
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence:')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print ('From Server:', modifiedSentence)
clientSocket.close()
This one is TCP Receiver.py
from socket import *
serverName = 'localhost'
serverPort = 8797
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
print ('The server is ready to receive')
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
print(sentence)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()

UDP packets not received in emulator from localhost

My app is unable to receive the UDP packets when running in the emulator. UDP packets are sent by below java program on "localhost" over the port 49999.
DatagramSocket clientsocket;
DatagramPacket dp;
BufferedReader br;
InetAddress ia;
byte buf[] = new byte[1024];
int cport = 50000, sport = 49999;
clientsocket = new DatagramSocket(cport);
dp = new DatagramPacket(buf, buf.length);
br = new BufferedReader(new InputStreamReader(System.in));
ia = InetAddress.getLocalHost();
while(true)
{
Random rand = new Random();
String str1 = rand.nextInt(100) + "";
buf = str1.getBytes();
System.out.println("Sending " + str1);
clientsocket.send(new DatagramPacket(buf,str1.length(), ia, sport));
try{
Thread.sleep(100);
} catch(Exception e){}
}
Another java UDP server program running on the same localhost receives the packets fine. This means that the packets are sent to localhost:49999 correctly.
To forward the packets from localhost to the emulator, I did telnet redirect as below:
telnet localhost 49999
redir add udp:49999:49999
The UDP receiver in the app looks like this:
byte[] data = new byte[1400];
DatagramPacket packet = new DatagramPacket(data, 1400);
DatagramSocket socket = new DatagramSocket(49999);
socket.setSoTimeout(200);
try{
socket.receive(packet); ---->> This throws a SocketTimeoutException
} catch(SocketTimeoutException e){}
My understanding was that the telnet redirect should take care of forwarding the packets from my development machine's localhost:49999 to emulator's localhost:49999 so that the data is available on the DatagramSocket(49999). However it keeps throwing the SocketTimeoutException all the time.
It would be a great help to know what is the missing piece of the puzzle here.
After connecting to the localhost you may want to check that the port was actually asigned as intended with the command netstat -na in the cmd. It also might be worth a try to use the IP 127.0.0.1 instead.

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

Request File from server using sockets

I am creating a program where an android device requests a file from a Web Server(running python).The server can receive over sockets with no problem the path of the requested file but i dont know how i can make my android device to wait for a responce.
Here is the android code(as a client requesting a file from web server):
try {
Socket socket = null;
socket = new Socket("192.168.1.9", 4000);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
String str = getURL();
output.writeBytes(str);
output.close();
input.close();
socket.close();
{
}
} catch (IOException e) {
}
Log.d("communicationService", "URL transferred with success");
And the python script running on Web Server(It can receive thefile path but i have problem sending the file)
import socket
import sys
HOST, PORT = '192.168.1.9', 4000
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind((HOST,PORT))
serverSocket.listen(10)
print 'Server is on and listening to %s ... ' % PORT
while True:
clientSocket, clientAddress = serverSocket.accept()
print 'A client was connected.....'
incomingURL = clientSocket.recv(1024)
print incomingURL
clientSocket.close()
Any advice and tip would be really helpful...
I imagine you should be able to get away with SimpleHTTPServer
If you need to get fancier with a full blown webservice, WSGI is very popular.
On the client side Requests library is by far the easiest way that I've found to make http requests in python. (just had to plug that one because it's that good)
Well i managed to transfer the files in the end(For those that are interested in apps of this kind).What i did was to create another socket and sent a stream back to client.
file = open("path_of_file", "rb")
s = socket.socket()
s = connect((addr,port))
l = file.read(1024)
while (l):
s.send(l)
l.f.read(1024)
file.close()
s.close()

My java chat client only sends strings when the dataStream is closed

I created a java chat application (client and server)
Everything works fine when I'm on my LAN (using LAN IP address of the server into my client).
But when I'm using the Internet address of my server in my client, the strings are sent only when I close the output Data stream of my client (and all the strings are sent at once).
Here's a quick snap of my code (I have port forward from 6791 to 6790 in the example below),
My server (thread):
// this line is actually on my global server class, used below with theServer
ServerSocket svrSocket= new ServerSocket(6790);
//wait for incoming connection
connectionSocket = svrSocket.accept();
connectionSocket.setSoTimeout(10000);
// free the accepting port
svrSocket.close();
//create a new thread to accept future connections (creates a new svrSocket)
theServer.openNewConnection();
//create input stream
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
boolean threadRunning = true);
while (threadRunning) {
//System.out.println("thread: in the while");
try {
Thread.sleep(100);
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
}
catch...
}
My client:
InetAddress dnsName;
Socket clientSocket;
PrintWriter out;
dnsName = InetAddress.getByName("myAddress.me");
clientSocket = new Socket(dnsName.getHostAddress(), 6791);
Thread.sleep(10);
out = new PrintWriter(clientSocket.getOutputStream(), true );
int i=140;
while (i>130){
try {
out.println(Integer.toString(i));
out.flush();
Thread.sleep(200);
}
catch(Exception e) {
e.printStackTrace();
}
i--;
}
out.flush();
out.close();
clientSocket.close();
I've tried with DataOutStreams, there's nothing to do.
My server will only receive the strings when out.close() is called on client side.
Is there a reason why, over the Internet, the data stream has to be closed for data to be sent? Is there a way around this? Am I doing something wrong?

Categories