简体   繁体   English

Python持久套接字连接

[英]Python persistent socket connection

I'm new to python :) I would like to create persistent socket. 我是python的新手:)我想创建持久套接字。 I tried to do this using file descriptors. 我试图使用文件描述符来做到这一点。 What I tried is: 我试过的是:

  1. Open a socket socket connection s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 打开一个套接字套接字连接s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  2. Get it's file descriptor number fd = s.fileno() 获取它的文件描述符号fd = s.fileno()

  3. Open the file descriptor as I/O os.open(fd) 以I / O os.open(fd)打开文件描述符

But I get OSError: [Errno 9] Bad file descriptor 但是我得到OSError: [Errno 9] Bad file descriptor

I said I'm new to python and maybe I'm wrong with the implementation. 我说我是python的新手,也许我的实现是错误的。 But I tried a simpler example os.close(s.fileno()) and I get the same error OSError: [Errno 9] Bad file descriptor 但是我尝试了一个更简单的示例os.close(s.fileno())并且得到了相同的错误OSError: [Errno 9] Bad file descriptor

I found an example written in ruby and I tested it, it works. 我找到了一个用ruby编写的示例,并对其进行了测试,它可以正常工作。 How do I make persistent network sockets on Unix in Ruby? 如何在Ruby中的Unix上建立持久性网络套接字?

Can any one write this into python for me, what I want to achieve is: socket_start.py google.com (thie will print the fd number) sleep 10 socket_write.py fd_number 'something' sleep 10 socket_read.py fd_number 1024 任何人都可以帮我把它写到python中吗,我想实现的是:socket_start.py google.com(那会打印fd号码)sleep 10 socket_write.py fd_number'something'sleep 10 socket_read.py fd_number 1024

I hope you understand what I want to do. 我希望你理解我想做什么。 Thanks in advice! 感谢您的建议!


After your responses I tried next code: 在您回复之后,我尝试了下一个代码:

1 1个

#!/usr/bin/python

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('google.com', 80))
s.send('GET /\n')
print s.fileno()

2 2

#!/usr/bin/python

import os
import sys

fd = int(sys.argv[1])
os.read(fd, 1024)

And the error is OSError: [Errno 9] Bad file descriptor 错误是OSError: [Errno 9] Bad file descriptor

I'm sure what the problem is (I'm a php developer). 我确定问题出在哪里(我是PHP开发人员)。 I think same as php, python deletes garbage after closing a script. 我认为和php一样,python在关闭脚本后删除垃圾。 How to solve this in python ? 如何在python中解决这个问题?

You use os.fdopen() to open file descriptors. 您使用os.fdopen()打开文件描述符。

I'm actually surprised that you got that far because os.open requires a filename and flags stating which mode to open the file in. for example fd = os.open('foo.txt', os.O_RONLY) . 我真的感到惊讶,因为os.open需要一个文件名标志来说明以哪种模式打开文件。例如fd = os.open('foo.txt', os.O_RONLY) As my example indicates, it returns a file descriptor rather than accepting one. 如我的示例所示,它返回文件描述符而不是接受文件描述符。

如果要通过命令行上收到的参数(即套接字)重新创建套接字,请使用socket.fromfd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM