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.
Related
Am new to Socket programming am trying to establish a communication between a Server and a client but i don't know how to do that am a bit confused on how to go about it. I have written the program below but it is given error and i can't get my head round why.
package server;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Server {
public static void main(String[] args) {
// TODO code application logic here
try {
DatagramSocket socket = new DatagramSocket(7000);
socket.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
String message = new String (buffer);
System.out.println(message);
String Reply ="Am here";
DatagramPacket data = new DatagramPacket(Reply.getBytes(), Reply.getBytes().length, packet.getAddress(), packet.getPort());
socket.send(data);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
Client
package client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main(String[] args) {
// TODO code application logic here
try{
String message = "Hello Server";
String host = "localhost";
InetAddress addr = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 7000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
DatagramSocket sockets = new DatagramSocket(7000);
sockets.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packets = new DatagramPacket(buffer,buffer.length);
sockets.receive(packets);
String messages = new String (buffer);
System.out.println(messages);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
How can i get them communicated. I have heard about Multi-threading but can't get my head round how it works.
I get the following error.
java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(DualStackPlainDatagramSocketImpl.java:84)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:93)
at java.net.DatagramSocket.bind(DatagramSocket.java:392)
at java.net.DatagramSocket.<init>(DatagramSocket.java:242)
at java.net.DatagramSocket.<init>(DatagramSocket.java:299)
at java.net.DatagramSocket.<init>(DatagramSocket.java:271)
at client.Client.main(Client.java:32)
If you wanting to send/receive from a client to a server using a socket then use ServerSocket on the serverside.
Then use accept - This listens for a connection to be made to this socket and accepts it.
The Socket object returned by Accept has Input and Output Stream which can be be read and written to.
The client will just use a Socket Object
See http://cs.lmu.edu/~ray/notes/javanetexamples/ for an example
If for some reason you insist on using DatagramSocket, then see this example https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
The error occurs because the port you are trying to bind your socket to is already in use. Port 7000 is used both by the client and server:
DatagramSocket sockets = new DatagramSocket(7000);
I'm working with a UDP Client (written in Java) and a Server (written in Lua). I'm using Lua Socket for the server and DatagramSockets for the client. Connection gets established successfully. The problem is when Lua server sends a string to the Java client, Java receive() function does not get the data and blocks. pls help me.
Lua server code:
-- Server
local socket = require("socket")
host = host or "*"
port = port or 8080
s = assert(socket.bind(host, port))
c = assert(s:accept())
data = "hello"
while true
do
assert(c:send(data .. "\n"))
socket.sleep(1)
-- return 0;
end
Java client code :
import java.net.*;
import java.io.*;
public class Clientnew
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = null;
byte[] Message = new byte[100];
try {
InetAddress IP = InetAddress.getLocalHost();
Socket client = new Socket(IP, 8080);
ds = new DatagramSocket(8080);
DatagramPacket dp = new DatagramPacket(Message, 1);
ds.receive(dp);
System.out.println("Recv\n");
String str = new String(dp.getData());
System.out.println(str);
} catch (Exception e)
{
} finally
{
if (ds != null)
{
ds.close();
}
}
}
}
Both program run on the Linux Platform.
Your Lua code is a TCP Server, not a UDP one. Also, remember that UDP is connectionless...
http://w3.impa.br/~diego/software/luasocket/udp.html
You can use standard tools like netstat to check things like this.
If I make a socket connection from an application that is running on an application server, where does the returned data go? Is it necessary to create a receiving server socket in the application with a specified port, or is it received on the port at which the server is using to connect to the application and I just need to write something that will extract that data?
Here is the code to read from a socket. You are making socket connection to port 8080 in server. You don't have to worry about the OS -> Server port.
public static void readSocket() throws IOException {
try (Socket s = new Socket(InetAddress.getByName(new URL("Some Address").getHost()), 8080);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
}
The socket is one end-point of two-way communication link between server and client programs of the network.
The returned data is sending to your client Socket object, lets call it clientSocket. You need to call clientSocket.getInputStream() to decode it.
No, you dont need to create a receiving server socket in the application. Your client program establishes a connection to the server on your given host and port. clientSocket can both send data to server and receive data from server.
For example the client side code:
private PrintWriter out = null;
private BufferedReader in = null;
public void listenSocket(){
//Create socket connection
try{
clientSocket = new Socket(HOST, PORT);
// use out object to send data to server applicaiton
out = new PrintWriter(clientSocket.getOutputStream(),
true);
// uses in object to receive data from server application
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + HOST);
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}
I just recently found the ServerSocket and Socket class found in the Java library and so I wanted to make a simple messaging app. The purpose of the app is to be able to communicate with someone on a different network than mine (I am the server side and have my own client side).
Here is the Messenger_Server.java's connecting method
public static void main (String [] args)throws IOException{
InetAddress ip;
try{
final int PORT = 444;
ip = InetAddress.getLocalHost();
ServerSocket server = new ServerSocket(PORT);
System.out.println("Waiting for clients...");
System.out.println(server.getInetAddress() + " " + ip.getHostAddress());
while(true){
Socket sock = server.accept();
connectionArray.add(sock);
System.out.println("Client connected from " + sock.getLocalAddress().getHostName());
addUserName(sock);
Messenger_Server_Return chat = new Messenger_Server_Return(sock);
Thread X = new Thread(chat);
X.start();
}
} catch(Exception e) {
e.printStackTrace();
}
}
Here is the client's connecting method from Messenger_Client.java
public static void connect(){
try{
final int PORT = 444;
// the ip below is the one i get as my ipv4
Socket sock = new Socket ("10.122.***.***",PORT);
System.out.println("you be connected to: " + InetAddress.getByAddress(InetAddress.getLocalHost().getAddress()));
chatClient = new Messenger_Client(sock);
PrintWriter out = new PrintWriter(sock.getOutputStream());
out.println(userName);
out.flush();
Thread X = new Thread(chatClient);
X.start();
}catch (Exception X){
X.printStackTrace();
JOptionPane.showMessageDialog(null, "Server not responding.");
System.exit(0);
}
}
So I gave the client side of the program to my friend and he said the host could not be found. Which IP should I use so my friend can connect to my ServerSocket, and could there be anything limiting my friend from connecting to me?
I am trying to establish communication between a SocketServer (Server) in Java and a Socket (Client) in php.
The client is able to connect to host, the client is able to send a message and the server reads the message successfully. But the problem arises when the SocketServer writes to the Client, the client does not receive the message from the server.
I have read the other questions on the same scenario (java-php socket communication) but i just can't seem to find what is causing the problem.
If i use a Java Socket as a client the communication works perfectly both ways.
The Server :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
protected ServerSocket socket;
protected final int port = 9005;
protected Socket connection;
protected String command = new String();
protected String responseString = new String();
public void init(){
System.out.println( "Launching Server: " );
try{
socket = new ServerSocket(port);
while(true)
{
// open socket
connection = socket.accept();
System.out.println( "Client Connected " );
// get input reader
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
BufferedReader input = new BufferedReader(inputStream);
// get input
command = input.readLine();
// process input
System.out.println("Command: " + command);
responseString = command + " MC2 It Works!";
// get output handler
PrintStream response = new PrintStream(connection.getOutputStream());
// send response
response.println(responseString);
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
The Client :
class Client {
private $address;
private $port;
public function __construct($address, $port){
$this->address = $address;
$this->port = $port;
$this->init();
}
private function init(){
//create socket
if(! $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'))){
$this->showError("socket create");
};
//establish connection
socket_connect($socket, $this->address, $this->port);
//write to server
$message = "I am a client";
socket_write($socket, $message, strlen($message)); //Send data
echo "Listening to Server\n";
//read from server
if(!$reponse = socket_read($socket, 2048, PHP_NORMAL_READ)){
$this->showError("socket read");
}
//print response
echo "Response from server------------------\n";
echo $reponse;
socket_close($socket);
}
private function showError($message){
echo ("Error: ".$message);
exit(666);
}
}
$address="localhost";$port=9005;
echo "Testing Client Server\n";
$client = new Client($address, $port);
Could someone please guide me to what could be the problem here ?
In server side, the code expects a line(terminated with linefeed), in php You send
socket_write($socket, $message, strlen($message));
Please check the data you send accordingly making sure that you send the linefeed character.