简体   繁体   English

.recv函数套接字编程Python中的TCP Server

[英].recv function Socket programming TCP Server in Python

Im having trouble getting my very basic and simple TCP Server to properly work with http requests. 我在让我非常基本和简单的TCP Server正确处理http请求方面遇到麻烦。 This is what I have so far 这就是我到目前为止

from socket import *
import sys 
serverSocket = socket(AF_INET, SOCK_STREAM)


serverSocket.bind(('', 4567))
serverSocket.listen(1)

while True:
    print('Ready to serve...')
    connectionSocket, addr =  serverSocket.accept()
    print("connected from: ", addr)
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]                 
        f = open(filename[1:])         
        outputdata = f.read()
        connectionSocket.send("HTTP/1.1 200 OK\r\n") 
        for i in range(0, len(outputdata)):           
            connectionSocket.send(outputdata[i].encode())
            connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        connectionSocket.send("file not found")
        serverSocket.close()
sys.exit()

The error comes from the open statement. 错误来自open语句。 I dont fully understand how this line of code's return value is organized. 我不完全了解这行代码的返回值是如何组织的。

message = connectionSocket.recv(1024)

I know that the return value is in bytes but when I try to use a fuction to turn it into a string like decode() i get errors as well 我知道返回值以字节为单位,但是当我尝试使用函数将其转换为类似decode()的字符串时,我也会遇到错误

I have the .py file and the html file sitting in the same directory on my local machine and the way I test this is I just run this and open up a browser and type in 我的.py文件和html文件位于本地计算机上的同一目录中,而我测试此方法的方式是运行并打开浏览器并输入

http://127.0.0.1:4567/helloworld.html

My code then promptly crashes after receiving the HTTP request. 我的代码在收到HTTP请求后立即崩溃。 Any and all help will be greatly appreciated! 任何和所有帮助将不胜感激!

There are numerous problems with your code and since you don't state what specific issues you are concerned about, here is what I see: 您的代码有很多问题,由于您没有说明要关注的特定问题,因此,我看到的是:

        connectionSocket.send(outputdata[i].encode())
        connectionSocket.send("\r\n".encode())

That appears to send a newline after every character you send back to the client. 在您发送回客户端的每个字符之后,似乎都会发送换行符。

Also, it doesn't deal with the client disconnecting because you're sending back invalid data. 另外,它不会处理客户端断开连接的问题,因为您正在发送回无效数据。

Even if what you were trying to do didn't have these errors in it, you don't appear to be attempting to send back a valid http response. 即使您尝试执行的操作中没有这些错误,您似乎也没有尝试发送回有效的http响应。

https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM