Java客户端在socket中

4
我很久以来一直在寻找使用Java连接创建在Python中的服务器的方法。谁可以向我展示如何连接并发送字符串?建议它也能在Android上工作。
我的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)

我的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();}

当Java客户端连接时,我从Python收到了一个错误。

    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提供的示例缩小问题的范围吗?我会运行在这里找到的服务器示例(https://docs.python.org/3/library/socket.html#example)而不包含回声组件。同时,你的防火墙可能正在阻止连接。如果你绑定到本地主机,它们通常允许连接工作。 - Deadron
1个回答

0

Python 回声服务器:

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客户端:
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();
      }
   }
}

最大的区别在于我正在将 localhost 转换为 localhost。如果您需要使 Python 服务器在 localhost 之外可用,请将 bind 行更改为:

soc.bind(("0.0.0.0", 6784))

这样服务器将会监听所有可用的接口。然后让你的Java客户端连接到服务器的外部IP。


为什么在Android中,我会在这一行代码 Socket client = new Socket("10.0.0.4", 7106); 中遇到错误? - Ziv Sion
@ZivSion,你遇到了什么错误?你需要确保已经导入了import java.net.Socket; - stdunbar
我有这个程序。关于错误,我不知道。它显示在运行中出现了错误。 - Ziv Sion
也许最好发布一个新帖子。确保捕获 Socket 代码中的任何异常以帮助调试。如果您打开了一个新帖子,请告诉我。 - stdunbar
好的,我会在5分钟内告诉你。 - Ziv Sion
我的新帖子是 https://stackoverflow.com/questions/65236804/android-send-and-get-socket-message-with-socket。 - Ziv Sion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接