亲宝软件园·资讯

展开

Python连接Java Socket服务端的实现方法

windSnowLi 人气:0
这篇文章主要介绍了Python连接Java Socket服务端的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

java服务端单线程示例

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Server
 */
public class Server {
  public static void main(String[] args) throws IOException {
    ServerSocket server = new ServerSocket(2580);
    Socket socket = server.accept();
    InputStream is = socket.getInputStream();
    OutputStream out=null;
    byte[] bytes = new byte[2048];
    int len = 0;
    String results = null;
    try {
      len = is.read(bytes, 0, 2048);
      results = new String(bytes, 0, len);
      System.out.println("from Client information:" + results);
      out=socket.getOutputStream();
      out.write("J-S-P_ I am Server".getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
    
    server.close();
    System.out.println("结束");

  }
}

Python客户端单线程示例

from socket import *

serverName = '127.0.0.1'
serverPort = 2580
BUFSIZ = 2048
ADDR = (serverName, serverPort)

clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(ADDR)
clientSocket.send("J-S-P_ I am Client".encode('utf-8'))
returnData = clientSocket.recv(BUFSIZ)
print('from Server information:%s' % returnData.decode('utf-8'))
clientSocket.close()
print("结束")

在这里插入图片描述

加载全部内容

相关教程
猜你喜欢
用户评论