python socket编程(socket)

代码如下:

server端:

import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host=socket.gethostname()
port=1234
s.bind((host,port))
s.listen(5)
while True:
c,addr=s.accept()
print("got connecion from:",addr)
while True:
msg=c.recv(1024).decode()
print("msg:",msg)
if not msg:
break
data="hello"
c.send(data.encode("utf-8"))
c.close()


client端:

import socket
host="server_name or ip"
port=1234
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
while True:
data=input("please input:")
if not data:
break
s.send(data.encode("utf-8"))
msg=s.recv(1024).decode()
if not msg:
break
print(msg)
s.close()

注意点:
1.port最好用大于1024的值。
2.client中的host要用server的IP或者主机名
3.数据的编码解码

可能报错及分析
1.ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
原因分析:服务器未启动
2.ConnectionResetError:  [WinError 10054] An existing connection was forcibly closed by the remote host
原因分析: 服务器突然关掉了

3. ConnectionAbortError: [WinError 10053] An established connection was aborted by the sofeware in youor host machine
原因分析:server端的代码在接收一个msg,发送一个data后就关闭了connection。应该在程序中加while循环,让不断的发送和接收

4.OsError: [WinError 10049] The requested address is not valid in its context
原因分析:代码中服务器hostname不对



原文地址:https://www.cnblogs.com/deadwood-2016/p/8317739.html