【发布时间】:2018-08-25 11:21:57
【问题描述】:
我正在尝试通过 nginx 处理套接字连接
- 我在某个端口(例如 9111)上启动服务器套接字,接受 套接字连接并尝试读取 2 个 POST 请求。
-
接下来,我启动套接字客户端,它连接到服务器套接字并发送 2 个 POST 请求。
- 当我在 9111 上启动客户端套接字时 - 一切正常。
- 当我在 80 上启动客户端套接字时(我们应该由 nginx 转发 到 9111 端口)- 只读取一条第一条消息。
请注意 - 它是简化的示例,内容主体为空以缩小它 - 我也尝试了很多 nginx 配置组合,连接头为空或'keep-alive'等
我做错了什么?
服务器端
val serverSock = new ServerSocket(9111)
println(s"Server socket started")
while (true) {
val sock = serverSock.accept()
val reader = new BufferedReader(new InputStreamReader(sock.getInputStream, "UTF8"))
println(s"Socket accepted: $sock")
println()
def readRequest() = {
println("Reading...")
var line = reader.readLine()
// Between headers and content should be empty line. Content is empty.
while (line != null && line.nonEmpty) {
println(s"Line: $line")
line = reader.readLine()
}
println("Request read.")
println()
}
readRequest()
readRequest()
sock.close()
}
客户端
// val sock = new Socket("localhost", 80) // Works incorrect. Only one message read on server side.
val sock = new Socket("localhost", 9111) // Works fine. Both messages read on server side.
val writer = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream, "UTF8"))
def postEmptyRequest(): Unit = {
writer.write("POST /socket HTTP/1.1\r\n")
writer.write(s"Host: 127.0.0.1\r\n")
writer.write(s"Content-Length: 0\r\n")
writer.write("Content-Type: application/x-www-form-urlencoded\r\n")
writer.write("\r\n")
writer.flush()
}
postEmptyRequest()
postEmptyRequest()
Thread.sleep(100)
sock.close()
nginx
server {
listen 80;
server_name localhost;
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:9111;
proxy_redirect off;
}
}
没有 nginx 的服务器端日志(端口 9111)
Server socket started
Socket accepted: Socket[addr=/127.0.0.1,port=60915,localport=9111]
Reading...
Line: POST /socket HTTP/1.1
Line: Host: 127.0.0.1
Line: Content-Length: 0
Line: Content-Type: application/x-www-form-urlencoded
Request read.
Reading...
Line: POST /socket HTTP/1.1
Line: Host: 127.0.0.1
Line: Content-Length: 0
Line: Content-Type: application/x-www-form-urlencoded
Request read.
使用 nginx(端口 80)的服务器端日志
Socket accepted: Socket[addr=/127.0.0.1,port=61089,localport=9111]
Reading...
Line: POST /socket HTTP/1.1
Line: X-Real-IP: 127.0.0.1
Line: X-Forwarded-For: 127.0.0.1
Line: Host: 127.0.0.1
Line: X-NginX-Proxy: true
Line: Content-Length: 0
Line: Content-Type: application/x-www-form-urlencoded
Request read.
Reading...
Request read.
【问题讨论】:
标签: java sockets nginx serversocket