zoukankan      html  css  js  c++  java
  • Python Socket编程

    1.直接上代码

    server:
    
    __author__ = 'Alex'
    #coding:utf-8
    import socket
    
    ip_port = ('127.0.0.1',8000)
    sk = socket.socket()
    sk.bind(ip_port)
    sk.listen(5)
    print ("服务端启动...")
    
    while True:
        conn,addr = sk.accept()
        while True:
            try:
                recv_data = conn.recv(1024)
                if len(recv_data) == 0:break
            except Exception as e:
                print ("意外中断")
                break
            print (str(recv_data,"utf8"))
            send_data = input(">>>>>>")
            conn.sendall(bytes(send_data,"utf8"))
        conn.close()
    
    ######################################################### client:
    __author__ = 'Alex' #coding:utf-8 import socket ip_port = ('127.0.0.1',8000) sk = socket.socket() sk.connect(ip_port) print ("客户端启动...") while True: send_data = input(">>>>>>>") if send_data == 'exit': break sk.send(bytes(send_data,"utf8")) recv_data = sk.recv(1024) print (str(recv_data,"utf8")) sk.close()

    这个程序里面要做几点说明:1,如果客户端发exit,那么服务端会接收到一个空字符串,因为可以通过对接收的字符串长度的判断来知道客户端是否退出了;2,如果客户端是通过程序终止的方式来关闭,那么服务器会收到一个Exception,那么服务端要对应的做异常处理(WINDOWS环境下),如果是LINUX的情况下,程序终止会导致服务端接收到空字符串。

    2.多消息并发,如果一个SERVER端想同时和多个CLIENT端进行通信,那么需要使用多线程或者IO多路复用,我们的socketserver.ThreadingTCPServer中封装了这样的功能。

    为什么我们要定义在handle方法中来实现,需要看继承关系:

    SERVER:
    
    __author__ = 'Alex'
    #coding:utf-8
    import socketserver
    
    class MyServer(socketserver.BaseRequestHandler):
    
        def handle(self):
            print ("服务端启动...")
            while True:
                conn = self.request
                print (self.client_address)
                while True:
                    recv_data = conn.recv(1024)
                    print (str(recv_data,"utf8"))
                    send_data = input(">>>>>>")
                    conn.sendall(bytes(send_data,"utf8"))
                conn.close()
    
    
    if __name__ == '__main__':
        server = socketserver.ThreadingTCPServer(('127.0.0.1',8999),MyServer)
        server.serve_forever()
    
    
    CLIENT:
    
    __author__ = 'Alex'
    #coding:utf-8
    import socket
    
    ip_port = ('127.0.0.1',8999)
    sk = socket.socket()
    sk.connect(ip_port)
    print ("客户端启动...")
    
    
    while True:
        send_data = input(">>>>>>>")
        # print (send_data)
        sk.send(bytes(send_data,"utf8"))
        if send_data == 'exit':
            # print ("It's True")
            break
        recv_data = sk.recv(1024)
    
        print (str(recv_data,"utf8"))
    sk.close()

    这样就可以实现一个服务端对多个客户端的通信了。

    __author__ = 'Alex'
    #coding:utf-8
    import socketserver
    import time
    class MyServer(socketserver.BaseRequestHandler):
    
        def handle(self):
            print ("服务端启动...")
            while True:
                conn = self.request
                print (conn)
                print (self.client_address)
                while True:
                    try:
                        time.sleep(5)
                        recv_data = conn.recv(1024)
                        print (str(recv_data,"utf8"))
                        if str(recv_data,"utf8") == 'exit':
                            print ("服务器发起了exit")
                            break
                        if len(recv_data) == 0:
                            print ("没有数据,请等待")
                            break
                    except Exception:
                        print ("意外中断")
                        break
    
                    print (str(recv_data,"utf8"))
                    send_data = input(">>>>>>")
                    conn.sendall(bytes(send_data,"utf8"))
                conn.close()
    
    
    if __name__ == '__main__':
        server = socketserver.ThreadingTCPServer(('127.0.0.1',8999),MyServer)
        server.serve_forever()
  • 相关阅读:
    JS-只能输入中文和英文
    强密码正则表达式
    java 实体序列化的意义
    数据库中存在0,1,2.....或者1,null,2 排序时让0或者null在最后的sql语句
    Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile 解决办法
    C#中的线程(二) 线程同步基础
    C#中的线程(一)入门
    C#多线程编程
    C#(asp.net )读取ASHX文件(一般处理程序)
    Oracle中三种循环(For、While、Loop)
  • 原文地址:https://www.cnblogs.com/python-study/p/5789530.html
Copyright © 2011-2022 走看看