Skip to content

Instantly share code, notes, and snippets.

@xiongxin
Created February 25, 2016 13:10
Show Gist options
  • Save xiongxin/de942b5f2698355adcbe to your computer and use it in GitHub Desktop.
Save xiongxin/de942b5f2698355adcbe to your computer and use it in GitHub Desktop.
nim sockets
import net
import rawsockets
import strutils
const SERVER_PORT = Port(1987)
const SERVER_ADDR = "localhost"
var canQuit = false
proc main() =
try:
var clientSocket = newSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, false)
var clientSocketFD = clientSocket.getFD()
clientSocketFD.setBlocking(false)
clientSocket.connect(SERVER_ADDR, SERVER_PORT, 2000)
while not canQuit:
var message: string
stdout.write("message: ")
message = stdin.readLine()
message.add("\c\l")
clientSocket.send(message)
if message == "exit\c\l":
clientSocket.close()
canQuit = true
except OSError:
echo("OSError")
main()
import net
const SERVER_PORT = Port(1987)
var canQuit = false
proc handleClient(clientSocket: Socket) =
var canStopReceiving = false
while not canStopReceiving:
var bufferString: string = ""
clientSocket.readLine(bufferString);
echo("Client: " & bufferString)
if bufferString == "exit":
clientSocket.close()
canQuit = true
canStopReceiving = true
proc main() =
try:
var serverSocket = newSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, true)
serverSocket.bindAddr(SERVER_PORT)
echo ("server", " is bound to port ", $SERVER_PORT)
serverSocket.listen()
echo ("server", " is listening for an incomming connection...")
var clientSocket = newSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, true)
var clientSocketFD = clientSocket.getFD()
clientSocketFD.setBlocking(false)
serverSocket.accept(clientSocket)
echo ("server", " has accepted a new connection from: $$$$")
handleClient(clientSocket)
serverSocket.close()
except OSError:
echo("OSError")
return
echo("finished...")
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment