欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python与Java之间Socket通信

程序员文章站 2022-03-24 11:37:25
...
  • python socket server
import socket
HOST = '192.168.1.38'
PORT = 50006

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.send("232132132131".encode())

szBuf = sock.recv(1024)
byt = 'recv:' + szBuf.decode('utf-8')
print(byt)

sock.close()

  • python socket client
import socket
HOST = '192.168.1.38'
PORT = 50006

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.send("232132132131".encode())

szBuf = sock.recv(1024)
byt = 'recv:' + szBuf.decode('utf-8')
print(byt)

sock.close()
  • java socket client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class SocketClient {

    public static void main(String args[])throws Exception {

        try {
            Socket socket = new Socket("192.168.1.38",50006);

            //获取输出流,向服务器端发送信息
            OutputStream os=socket.getOutputStream();//字节输出流
            PrintWriter pw=new PrintWriter(os);//将输出流包装为打印流
            pw.write("我是Java服务器");
            pw.flush();
            socket.shutdownOutput();//关闭输出流

            InputStream is=socket.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String info=null;
            while((info=in.readLine())!=null){
                System.out.println("我是客户端,Python服务器说:"+info);
            }
            is.close();
            in.close();
            socket.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 值得注意的是,这里的服务器域名应该写本电脑上的ip,而不是127.0.0.1

来自: http://blog.csdn.net/ChenTianSaber/article/details/52274257?locationNum=4