Best way to open a socket in Python

2019-01-22 11:26发布

I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?

3条回答
我想做一个坏孩纸
2楼-- · 2019-01-22 11:32

OK, this code worked

s = socket.socket()
s.connect((ip,port))
s.send("my request\r")
print s.recv(256)
s.close()

It was quite difficult to work that out from the Python socket module documentation. So I'll accept The.Anti.9's answer.

查看更多
Rolldiameter
3楼-- · 2019-01-22 11:49

For developing portable network programs of any sort in Python, Twisted is quite useful. One of its benefits is providing a convenient layer above low-level socket APIs.

查看更多
Evening l夕情丶
4楼-- · 2019-01-22 11:54

Opening sockets in python is pretty simple. You really just need something like this:

import socket
sock = socket.socket()
sock.connect((address, port))

and then you can send() and recv() like any other socket

查看更多
登录 后发表回答