zoukankan      html  css  js  c++  java
  • 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不对



  • 相关阅读:
    mac PHP安装imageMagic扩展
    使用AWS Lambda,API Gateway和S3 Storage快速调整图片大小
    composer Changed current directory to没反应
    mongodb批量update更新数据
    php 判断图片文件的真实类型
    C#选择文件、选择文件夹、打开文件(或者文件夹)
    C#连接数据库
    湿寒阳虚体质如何艾灸
    女人艾灸穴位
    四个穴位掌控全身健康
  • 原文地址:https://www.cnblogs.com/deadwood-2016/p/8317739.html
Copyright © 2011-2022 走看看