What is protocol I can use for connection? - java

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

Related

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

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

Python socket problems on server side

On the python server i plan to receive parameters from a java client, run them through a neural network and send the result back. The messages will be numpy arrays converted to strings for the communication process.
However i'am not that far yet trying to pass some dummy string from the client just to envoke the server routine and everything is fine when i just send a string back. However when i call mod.predict(arr) INSIDE the loop or do not concatenate the received data to the reply, the server doesn't react. Does anyone have an idea how i could get this done?
Server - Python:
HOST = 'localhost'
PORT = 7777
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
while True:
conn, addr = s.accept()
data = conn.recv(1024)+"\r\n"
pred = mod.predict(arr)
reply = 'Answer..' + pred + data # +'\r\n'
if not data:
break
conn.send(reply)
conn.close()
Client - Java:
Socket socket = new Socket("localhost", 7777);
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out, true);
ps.println("Hello Python!");
InputStream in = socket.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(in));
while (buff.ready()) {
System.out.println(buff.readLine());
}
socket.close();
Server code:
import socket
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.bind(("localhost", 5000))
sock.listen()
while True:
try:
sock.listen()
conn, addr = sock.accept()
print(conn.recv(1024))
conn.send(b"Hello world from Python")
conn.close()
except:
break
sock.close()
This is correct, because cURL says so.
➜ ~ curl -v localhost:5000
* Rebuilt URL to: localhost:5000/
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> GET / HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
>
* Connection #0 to host localhost left intact
Hello world from Python%
Oh, and your client code is wrong as well. You need to create a streaming socket, not a datagram socket (which is what you have).
Client code:
import java.net.*;
import java.io.*;
class Main
{
public static void main(String args[]) throws Exception
{
// This constructor creates a streaming socket
Socket socket = new Socket(InetAddress.getByName(null), 5000);
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out, true);
ps.println("Hello Python!");
InputStream in = socket.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(in));
while (buff.ready()) {
System.out.println(buff.readLine());
}
socket.close();
}
}
This is what the server code looks like now. All expressions are calculated and printed correctly in the console when i start the server from commandline and then run the java-client from eclipse. What really is strange is that when i pass some string as reply and it seem to work, it can stop working when i just add some print argument in the while loop like in the code below.
import socket
import sys
import pickle
import numpy as np
f=open('C:\\nn.pkl','rb')
mod=pickle.load(f)
HOST = 'localhost'
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.bind((HOST, PORT))
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
while True:
try:
s.listen(10)
conn, addr = s.accept()
data = conn.recv(1024)
print data
arr = np.array([1.0, 0.9712, 0.01019, 0.333, 0.01008, 0.5625, 0.75, 0.4, 0.25, 0.6, 0.0])
pred = np.array_str(mod.predict(arr))
print pred
reply = "Answer.." + pred
conn.send(reply)
conn.close()
except:
break
s.close()
Additionaly when i repeatedly run the java client while the server is running, i somtimes get an answer and somtimes not because buff.ready() isn't true on every run.
public static void main(String args[]) throws IOException {
Socket socket = new Socket(InetAddress.getByName(null), 5000);
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out, true);
ps.println("Hello Python!");
InputStream in = socket.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(in));
while (buff.ready()) {
System.out.println(buff.readLine());
}
}

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.

Categories