Python和Java跨语言socket通信

Python + Java socket

Python和Java跨语言socket通信_第1张图片

纯Python

服务端

import socket

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)# 套接字类型AF_INET, socket.SOCK_STREAM   tcp协议,基于流式的协议
s.bind(('127.0.0.1', 8080))
s.listen(1) # 最多可以连接多少个客户端
output = '我是服务端'
while 1:
    print('服务器正在接受...')
    # 阻塞等待,创建连接
    conn, addr = s.accept()
    data = conn.recv(1024).decode('utf-8')
    print(f'接收到客户端发过来的数据: {data}')
    conn.sendall(output.encode('utf-8'))
    conn.close()

客户端

import socket

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8080))
s.sendall('我是客户端'.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
print(f'接收到服务端返回数据: {data}')
s.close()

收发记得要用二进制,发的时候把字符串用encode编码,收的时候用decode解码

JAVA服务端,Python客户端

JAVA

package socket_demo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
public class socket_demo {
   public static void main(String[] args) {
      try {
         ServerSocket ss = new ServerSocket(8888);
         System.out.println("启动服务器....");
         Socket s = ss.accept();
         System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
         
         BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
         //读取客户端发送来的消息
         String mess = br.readLine();
         System.out.println("客户端:"+ mess);
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
         bw.write(mess+"\n");
         bw.flush();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Python

import socket

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
print(1)
s.sendall(b'abcd\n')
print(2)
data = s.recv(1024).decode('utf-8')
print(f'接收到服务端返回数据: {data}')
s.close()

python发送数据的时候需要后面添加\n或\r

你可能感兴趣的:(开发,python,python)