swiftsocket / SwiftSocket

The easy way to use sockets on Apple platforms
BSD 3-Clause "New" or "Revised" License
1.68k stars 400 forks source link

An existing connection was forcibly closed by the remote host #195

Open pekochun opened 4 years ago

pekochun commented 4 years ago

I used the following Python code as a client.

import socket

target_ip = "192.168.1.3"
target_port = 8080
buffer_size = 4096

i = 0
while True:
    if i == 10000:
        break

    tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    tcp_client.connect((target_ip,target_port))
    tcp_client.send(str(i).encode())

    response = tcp_client.recv(buffer_size)
    print("[*]Received a response : {}".format(response))
    i = i + 1

Then, I ran the following server code in Swift.

func echoService(client: TCPClient) {
    print("Newclient from:\(client.address)[\(client.port)]")
    var d = client.read(1024*10)
    client.send(data: d!)
    client.close()
}

func testServer() {
    let server = TCPServer(address: "192.168.1.3", port: 8080)
    switch server.listen() {
      case .success:
        while true {
            if var client = server.accept() {
                echoService(client: client)
            } else {
                print("accept error")
            }
        }
      case .failure(let error):
        print(error)
    }
}

The code ran normally up to the 400th time, but after about 400 times, an error occurred in Python.

The error details are as follows

An existing connection was forcibly closed by the remote host

Does anyone know what causes this error?