After successfully connected to a tcp socket server, how can i sent the messages to that server?
i have created this client, and is working fine as long as is a two way communication with the server REPLYING FIRST.
final Flow<ByteString, ByteString, CompletionStage<Tcp.OutgoingConnection>> connection =
Tcp.get(system).outgoingConnection("127.0.0.1", 8888);
final Flow<ByteString, ByteString, NotUsed> repl = Flow.of(ByteString.class)
.map(ByteString::utf8String)
.map(
text -> {
System.out.println("Server: " + text);
return "next";
}
)
.map(ByteString::fromString);
CompletionStage<Tcp.OutgoingConnection> connectionCS = connection.join(repl).run(system);
after handshake, i need to send the credentials, AND I HAVE NO IDEA HOW.
in plain java it would be something like that:
SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket)factory.createSocket(hostname, 8888);
socket.setReceiveBufferSize(1024 * 1000 * 2);
socket.startHandshake();
PrintWriter out = this.getPrintWriter(socket);
BufferedReader in = this.getBufferedReader(socket);
out.write(Authentication.getAsJson(loginApi.getAuthToken()));
out.write(CRLF);
out.flush();
`
Related
I have started a client in my system. It is running on port no 7913. I am sending a request data via TCP/IP from Java to server socket running on 7913.
log is Message sent to Socket [addr=/190.161.153.109,port=7913,localport=54717]
I have also received the response from server for that particular data. Now the server is also trying to send a request to my localport 54717, not to port where my application is listening [ie 7913].
How to handle the request? When I try to connect with telnet to my localport, connection is refused.
The code:
public static String ickTransport(String ickHeader,String ickdata, Socket connection) throws UnknownHostException, IOException
try
{
connection.setSoTimeout(Integer.parseInt(ickTimeOut));
log.debug("ick Message for "+connection.toString()+" is " + ickMessage);
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
DataOutputStream osw = new DataOutputStream(bos);
osw.writeShort(Integer.parseInt(ickHeader));
osw.writeBytes(ickMessage);
osw.flush();
DataInputStream stream = new DataInputStream(connection.getInputStream());
int numberRecords = stream.readShort();
if (numberRecords > 0) {
int nSizeRead = 0;
byte[] bRequest = new byte[numberRecords];
int nSizeBuffer;
for (; numberRecords > 0; numberRecords -= nSizeBuffer) {
byte[] bBuffer = new byte[numberRecords];
nSizeBuffer = stream.read(bBuffer);
System.arraycopy(bBuffer, 0, bRequest, nSizeRead, nSizeBuffer);
nSizeRead += nSizeBuffer;
}
ickResponse = new String(bRequest);
log.debug("Response from ick is " + ickResponse);
}
}
catch (SocketTimeoutException e)
{
log.error(e.getMessage());
}
return ickResponse;
To understand what is going on you should understand what is listen socket and how it differs from connection socket.
When your application listens it (this ServerSocket does):
Attaches to the port that you specify in bind request or in constructor
Ask JVM to receive new connection on that port
When connection is received listen socket changes it state and provide you new socket for new connection with accept method.
When your application establishes NEW connection it use connect method. Unless you use bind request on socket it:
Allocates new dynamic port (54717 in your example)
Sends connect request to the server
After connection established you can use it for sending/receiving requests to/from server
Because nobody listens this dynamic port telnet requests are refused on it.
This question already has an answer here:
java.net.ConnectException: Connection refused TCP
(1 answer)
Closed 6 years ago.
I have to establish a TCP connection to a server, which requires that I send the credential to logon in the format:
<STX>username=fred&password=123456<ETX>
Let's say host: qstage.thetcphost.com and port:8999
I am new to socket programming and using the same to implement this. I have used java.net.Socket at the client side but I dont know how do I send the above string for authentication to the TCP Server in Java.
I am able to telnet the server now.
But how do I pass the credential string in the < STX >...< ETX > format after (or during):
Socket socket = new Socket("mshxml.morningstar.com", 8999);
I mean what is the piece of code that I have to write to authenticate myself to the TCP server?
I have searched this site for this info but could not find any.
Help would be greatly appreciated.
Establish the socket connection is the first step before you can send any creds information.
If this step is failing, consider the specs from your target server. Is the correct port provided? Any consideration on protocol?
Usually, the authentication will be happen after you have already established successfully the connection.
Editted: Add source code for writing to socket from a socket client.
Now, in this context, you're a socket client, try to send creds to server.
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName +
" on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
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();
}
}
}
Sample found here: http://www.tutorialspoint.com/java/java_networking.htm
I want to do UDP Hole Punching with two clients with the help of a server with a static IP. The server waits for the two clients on port 7070 and 7071. After that it sends the IP address and port to each other. This part is working fine. But I'm not able to establish a communication between the two clients. I tried the code in different Wifi networks and in 3G mobile network. The client program throws the IO-Exception "No route to host".
The client code is used for both clients. Once executed with port 7070 and once with 7071.
Do you think I've implemented the UDP hole punching concept correctly? Any ideas to make it work?
Here's the server code first, followed by the client code.
Thank you for help.
Code of server:
public class UDPHolePunchingServer {
public static void main(String args[]) throws Exception {
// Waiting for Connection of Client1 on Port 7070
// ////////////////////////////////////////////////
// open serverSocket on Port 7070
DatagramSocket serverSocket1 = new DatagramSocket(7070);
System.out.println("Waiting for Client 1 on Port "
+ serverSocket1.getLocalPort());
// receive Data
DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
serverSocket1.receive(receivePacket);
// Get IP-Address and Port of Client1
InetAddress IPAddress1 = receivePacket.getAddress();
int port1 = receivePacket.getPort();
String msgInfoOfClient1 = IPAddress1 + "-" + port1 + "-";
System.out.println("Client1: " + msgInfoOfClient1);
// Waiting for Connection of Client2 on Port 7071
// ////////////////////////////////////////////////
// open serverSocket on Port 7071
DatagramSocket serverSocket2 = new DatagramSocket(7071);
System.out.println("Waiting for Client 2 on Port "
+ serverSocket2.getLocalPort());
// receive Data
receivePacket = new DatagramPacket(new byte[1024], 1024);
serverSocket2.receive(receivePacket);
// GetIP-Address and Port of Client1
InetAddress IPAddress2 = receivePacket.getAddress();
int port2 = receivePacket.getPort();
String msgInfoOfClient2 = IPAddress2 + "-" + port2 + "-";
System.out.println("Client2:" + msgInfoOfClient2);
// Send the Information to the other Client
// /////////////////////////////////////////////////
// Send Information of Client2 to Client1
serverSocket1.send(new DatagramPacket(msgInfoOfClient2.getBytes(),
msgInfoOfClient2.getBytes().length, IPAddress1, port1));
// Send Infos of Client1 to Client2
serverSocket2.send(new DatagramPacket(msgInfoOfClient1.getBytes(),
msgInfoOfClient1.getBytes().length, IPAddress2, port2));
//close Sockets
serverSocket1.close();
serverSocket2.close();
}
Code of client
public class UDPHolePunchingClient {
public static void main(String[] args) throws Exception {
// prepare Socket
DatagramSocket clientSocket = new DatagramSocket();
// prepare Data
byte[] sendData = "Hello".getBytes();
// send Data to Server with fix IP (X.X.X.X)
// Client1 uses port 7070, Client2 uses port 7071
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, InetAddress.getByName("X.X.X.X"), 7070);
clientSocket.send(sendPacket);
// receive Data ==> Format:"<IP of other Client>-<Port of other Client>"
DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
clientSocket.receive(receivePacket);
// Convert Response to IP and Port
String response = new String(receivePacket.getData());
String[] splitResponse = response.split("-");
InetAddress ip = InetAddress.getByName(splitResponse[0].substring(1));
int port = Integer.parseInt(splitResponse[1]);
// output converted Data for check
System.out.println("IP: " + ip + " PORT: " + port);
// close socket and open new socket with SAME localport
int localPort = clientSocket.getLocalPort();
clientSocket.close();
clientSocket = new DatagramSocket(localPort);
// set Timeout for receiving Data
clientSocket.setSoTimeout(1000);
// send 5000 Messages for testing
for (int i = 0; i < 5000; i++) {
// send Message to other client
sendData = ("Datapacket(" + i + ")").getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
clientSocket.send(sendPacket);
// receive Message from other client
try {
receivePacket.setData(new byte[1024]);
clientSocket.receive(receivePacket);
System.out.println("REC: "
+ new String(receivePacket.getData()));
} catch (Exception e) {
System.out.println("SERVER TIMED OUT");
}
}
// close connection
clientSocket.close();
}
UPDATE
The code is generally working. I've tried it in two different home networks now and it's working. But it isn't working in my 3G or university network. In 3G, I verified that the NAT is mapping the two ports (the client port and by the router assigned port) together again, even after closing and opening the clientSocket. Has anyone an idea why it isn't working then?
UDP hole punching can't be achieved with all types of NAT. There is no universal or reliable way defined for all types of NAT. It is even very difficult for symmetric NAT.
Depending on the NAT behaviour, the port mapping could be different for different devices sending the UDP packets.
Like, If A sends a UDP packet to B, it may get some port like 50000. But if A sends a UDP packet to C, then it may get a different mapping like 50002. So, in your case sending a packet to server may give a client some port but sending a packet to other client may give some other port.
You shall read more about NAT behaviour here:
https://www.rfc-editor.org/rfc/rfc4787
https://www.rfc-editor.org/rfc/rfc5128
UDP hole punching not going through on 3G
For symmetric NAT (3G network connecting to a different mobile network), you need to do Multi-UDP hole punching.
See:
https://drive.google.com/file/d/0B1IimJ20gG0SY2NvaE4wRVVMbG8/view?usp=sharing
http://tools.ietf.org/id/draft-takeda-symmetric-nat-traversal-00.txt
https://www.goto.info.waseda.ac.jp/~wei/file/wei-apan-v10.pdf
http://journals.sfu.ca/apan/index.php/apan/article/view/75/pdf_31
Either that or relay all the data through a TURN server.
You rightly use a rendezvous server to inform each node of the others IP / port based on the UDP connection. However using the public IP and port which is the combination which will is obtained by the connection as you have, means that in scenarios where both hosts exist on the same private network hairpin translation is required by the NAT which is sometimes not supported.
To remedy this you can send the IP and port your node believes itself to have in the message to the server (private ip / port) and include this in the information each node receives on the other. Then attempt a connection on both the public combination (the one you are using) and the one I just mentioned and just use the first one which is successfully established.
trying to connect via TCP to a server using java sockets, the connection gets refused. I'm supposed to send a key to authenticate. code:
Socket clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress("server.address.whatever", 123456));
System.out.println("Connected");
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String key = "key";
outToServer.writeBytes(key + "\r\n");
String response = inFromServer.readLine();
System.out.println("FROM SERVER: " + response);
clientSocket.close();
It never makes it to the point where it tries to print out "Connected", it throws
java.net.ConnectException: Connection refused
So i never send the key. What am i missing here? How can i send an initial message during connecting? Am i even supposed to do that?
It sounds like there is no server process listening on that socket. Check whether you can make a connection with a tool like nmap (or just telnet).
i'm trying to find out how to create a TCP server with SSL in java. But i don't get what i really need. Do i have to import key-files into java, and i so, how to do this? Or do i just need to change the type of the socket from Socket to SSLSocket? I've read some articles but couldn't find anything helpful because all of them just take http for communicating. I would need it for my own protocol. In my case it would be to have a program like this:
int port = 4444;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Started server on port " + port);
// repeatedly wait for connections, and process
while (true) {
// a "blocking" call which waits until a connection is requested
Socket clientSocket = serverSocket.accept();
System.err.println("Accepted connection from client");
// open up IO streams
In in = new In (clientSocket);
Out out = new Out(clientSocket);
// waits for data and reads it in until connection dies
// readLine() blocks until the server receives a new line from client
String s;
while ((s = in.readLine()) != null) {
out.println(s);
}
// close IO streams, then socket
System.err.println("Closing connection with client");
out.close();
in.close();
clientSocket.close();
}
to use a SSL connection. So how to do this?
Thanks,
Thomas
I found this with a quick Google search.
Here.