Created
February 25, 2016 13:10
-
-
Save xiongxin/de942b5f2698355adcbe to your computer and use it in GitHub Desktop.
nim sockets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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