Java client in socket

Viewed 60

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
1 Answers

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