TCP
- Server
from socket import *
HOST = "127.0.0.1"
PORT = 12345
ADDR = (HOST, PORT)
server = socket (AF_INET, SOCK_STREAM)
server.bind (ADDR)
server.listen (5)
print ("start listen...")
client, addr = server.accept ()
print ("accept a connection from %s" % str (addr))
data = client.recv (1024)
if not data:
print ("there is no data")
print ("exit the server process")
exit ()
print ("received a msg from client : %s" % str (data, encoding = "utf-8"))
client.send (bytes ("Server received.", encoding = "utf8"))
client.close ()
exit ()
- Client
from socket import *
HOST = "127.0.0.1"
PORT = 12345
ADDR = (HOST, PORT)
client = socket (AF_INET, SOCK_STREAM)
client.connect (ADDR)
client.send (bytes ("hehe", encoding = "utf8"))
data = client.recv (1024)
print ("Receive data : %s" % str (data, encoding = "utf-8"))
print ("close socket")
client.close ()
exit ()
说明:
- 必须用from socket import *,不能用import socket
- 使用print ()函数时,可以用 print (“xxx %s” % m_str)格式化输出字符串,也可以用 print (“xxx”, m_str) 连接多个字符串
- 程序中 addr 是一个tuple,不能在 print 中这样写:
print ("xxx %s" % addr)
,会报错的。可以这样写:print ("xxx %s" % str (addr))
- 调用 send () 函数时,必须把要发送的字符串转换成 bytes 格式才能发送。注意在使用 bytes () 函数的时候,编码时写utf8,解码时写utf-8,有一个短横杠的区别。