PureSwift / Socket

Swift async/await based socket
MIT License
116 stars 7 forks source link

Is there any example to use Socket as a TCP client? #3

Closed kkebo closed 2 years ago

kkebo commented 2 years ago

Firstly, thank you for this interesting project.

I'm attempting to create a TCP client using Socket.

I already tried the following code:

import Socket

@main
struct App {
    static func main() async throws {
        let socket = try await Socket(IPv4Protocol.tcp)
        defer { Task { await socket.close() } }
        let address = IPv4SocketAddress(address: .init(127, 0, 0, 1), port: 8620)
        try await socket.fileDescriptor.connect(to: address, sleep: 1_000_000)
        try await socket.write(.init("foobar".utf8))
        print("sent")
    }
}

but it didn't work and threw the following error:

Swift/ErrorType.swift:200: Fatal error: Error raised at top level: Socket is already connected

Does anyone know any good example for this use case? Thanks.

kkebo commented 2 years ago

P.S. I was running the server by this way.

nc -l 127.0.0.1 8620
kennethlaskoski commented 2 years ago

Swift/ErrorType.swift:200: Fatal error: Error raised at top level: Socket is already connected

I get the same error. As a workaround I'm catching the exception and ignoring it.

do {
  try await socket.fileDescriptor.connect(to: address, sleep: 1_000_000_000)
} catch Errno.socketIsConnected {}