其他分享
首页 > 其他分享> > socket 服务端 | socket 客户端 -->黏包现象

socket 服务端 | socket 客户端 -->黏包现象

作者:互联网

# ### 服务端
import socket
import time
sk = socket.socket()

# 在bind方法之前加上这句话,可以让一个端口重复使用
sk.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
# 绑定地址端口(在网络上注册主机)
sk.bind( ("127.0.0.1",9000) )
sk.listen()

conn,addr = sk.accept()
conn.send("6".encode("utf-8"))
message = "hello,"
conn.send(message.encode("utf-8"))
# time.sleep(0.1)
conn.send("world".encode("utf-8"))


# 四次挥手
conn.close()
# 退还端口
sk.close()


# ### 客户端
import socket
import time
sk = socket.socket()
sk.connect( ("127.0.0.1",9000) )

# time.sleep(0.2)
res0 = int(sk.recv(1).decode("utf-8")) #res0 "6"
print(res0)
res1 = sk.recv(res0)
print(res1)
# print(res1.decode("utf-8"))
res2 = sk.recv(10)
print(res2)
sk.close()
----------------------------------------------------------------------------------------------
# ### 服务端
import socket
import time
sk = socket.socket()

# 在bind方法之前加上这句话,可以让一个端口重复使用
sk.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
# 绑定地址端口(在网络上注册主机)
sk.bind( ("127.0.0.1",9000) )
sk.listen()

conn,addr = sk.accept()
conn.send("00000120".encode("utf-8"))
message = "hello," * 20
conn.send(message.encode("utf-8"))
# time.sleep(0.1)
conn.send("world".encode("utf-8"))


# 四次挥手
conn.close()
# 退还端口
sk.close()

# ### 客户端
import socket
import time
sk = socket.socket()
sk.connect( ("127.0.0.1",9000) )

# time.sleep(0.2)
res0 = int(sk.recv(8).decode("utf-8")) #res0 "6"
print(res0)
res1 = sk.recv(res0)
print(res1)
# print(res1.decode("utf-8"))
res2 = sk.recv(10)
print(res2)
sk.close()
------------------------------------------------------------------------------------------------
# ### 服务端
import socket
import struct

sk = socket.socket()
sk.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sk.bind( ("127.0.0.1",9000) )
sk.listen()

conn,addr = sk.accept()
inp = input(">>>msg:")
msg = inp.encode("utf-8")
# 发送数据的长度通过pack进行转换,变成具有固定长度的4个字节的值
res = struct.pack("i",len(msg))

conn.send(res)
# 接下来,开始真正的发送数据
conn.send(msg)
conn.send("world".encode("utf-8"))

res = conn.recv(1024)
print(res)
print(res.decode("utf-8"))
# 四次挥手
conn.close()
# 退还端口
sk.close()

# ### 客户端
import socket
import struct
import time
sk = socket.socket()
sk.connect( ("127.0.0.1",9000) )
time.sleep(0.1)
# 接受4个字节长度, 他是实际要发送的那个数字转化来的.
n = sk.recv(4)
n = struct.unpack("i",n)[0]
print(n)

# 接下来接受服务端发送过来的数据
res1 = sk.recv(n)
print(res1.decode("utf-8"))
res2 = sk.recv(1024)
print(res2.decode("utf-8"))

# 空格不是ascii编码中的,大家注意.
sk.send(b"i_love_you")

# 关闭连接
sk.close()

  

标签:utf,socket,黏包,sk,服务端,print,import,conn
来源: https://www.cnblogs.com/huangjiangyong/p/10960947.html