Python 3中套接字编程中遇到TypeError: 'str' does not support the buffer interface的解决办法_踏实的做好自己-CSDN博客 将往上的代码从2改到3

#!/usr/bin/env python
#-*- coding:utf-8 -*-
 
import socket
import select
import queue
 
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ("127.0.0.1", 8888)
serversocket.bind(server_address)
serversocket.listen(10)
serversocket.setblocking(False)  
timeout = 10
epoll = select.epoll()
epoll.register(serversocket.fileno(), select.EPOLLIN)
message_queues = {}
fd_to_socket = {serversocket.fileno():serversocket,}
 
while True:
  events = epoll.poll(timeout)
  if not events:
     continue
  
  for fd, event in events:
     socket = fd_to_socket[fd]
     if socket == serversocket:
            connection, address = serversocket.accept()
            connection.setblocking(False)
            epoll.register(connection.fileno(), select.EPOLLIN)
            fd_to_socket[connection.fileno()] = connection
            message_queues[connection]  = queue.Queue()
     elif event & select.EPOLLHUP:
        epoll.unregister(fd)
        fd_to_socket[fd].close()
        del fd_to_socket[fd]
     elif event & select.EPOLLIN:
        data = socket.recv(1024)
        if data:
           message_queues[socket].put(data)
           epoll.modify(fd, select.EPOLLOUT)
     elif event & select.EPOLLOUT:
        try:
           msg = message_queues[socket].get_nowait()
        except queue.Empty:
           print (socket.getpeername() , " queue empty")
           epoll.modify(fd, select.EPOLLIN)
        else :
           socket.send(msg)
 
epoll.unregister(serversocket.fileno())
epoll.close()
serversocket.close()
[root@localhost python-test]# cat client.py 

#!/usr/bin/env python
#-*- coding:utf-8 -*-
 
import socket
 
clientsocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_address = ('127.0.0.1',8888)
clientsocket.connect(server_address)
 
while True:
    data = input('please input:')
    clientsocket.sendall(data.encode())
    server_data = clientsocket.recv(1024).decode()
    print('receive server data :', server_data)
[root@localhost python-test]# python client.py 
please input:aaaa
receive server data : aaaa
please input:111111111111
receive server data : 111111111111
please input:33333333
receive server data : 33333333
please input:asfasdfsad
receive server data : asfasdfsad
please input:asfsadfasdf
receive server data : asfsadfasdf
please input:asdfasdfsaf
receive server data : asdfasdfsaf
please input:

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐