list/array of sockets in python

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

I am kind of new to python. I am currently trying to make and use a list/array of sockets in a program. So I have declared an array as follows:

myCSocks = ['CSock1', 'CSock2', 'CSock3', 'CSock4', 'CSock5']

And I am trying to use my array elements as follows:

myCSocks[i], addr = serverSocket.accept() message = myCSocks[i].recv(1024)

I am getting the following error:

Traceback (most recent call last):   File "./htmlserv_multi.py", line 22, in <module>     message = myCSocks[i].recv(1024) AttributeError: 'str' object has no attribute 'recv'

This kind of makes sense to me, it is saying that my array elements are of type String and are not sockets. So I understand what my problem is but I do not know how to remedy it. I have googled "list of sockets python" but did not find anything. Any help will be greatly appreciated. Thank you.

PS: My final objective is to create a very simple multithreaded TCP web server (using python)

CODE:

#! /usr/bin/env python from socket import *  #does this work? myCSocks = []  serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('192.168.1.4',12000)) serverSocket.listen(5) while True:   for i in range(0, len(myCSocks)+1):     myCSocks[i], addr = serverSocket.accept()   try:     for i in range(0, len(myCSocks)):       message = myCSocks[i].recv(1024)       filename = message.split()[1]       f = open(filename[1:])       outputdata = f.read()       myCSocks[i].send('HTTP/1.1 200 OK\r\n\r\n')       for p in range(0, len(outputdata)):         myCSocks[i].send(outputdata[p])       myCSocks[i].close()   except IOError:     connectionSocket.send('HTTP/1.1 404 Bad Request\r\n\r\n')     connectionSocket.send('<HTML><p>ERROR 404: BAD REQUEST!</p></HTML>')     serverSocket.close()     exit()

回答1:

Have a look at the built-in socket module here (http://docs.python.org/2/library/socket.html). This allows you to create sockets, and send and receive data, and there are simple examples in the online documentation. Your code will probably work if you replace the strings with actual sockets. If you want to store several sockets by name, you could use a dictionary:

theDict = {} theDict['socket1'] = socket.socket()

etc.



回答2:

If CSock1 is a class already defined you can just refer to the class objects. However, if you are trying to do a multi-threaded, there's better ways to do that: Multithreaded web server in python. If you are just trying to use sockets, I'd look at Multi Threaded TCP server in Python (the second answer is best).



转载请标明出处:list/array of sockets in python
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!