Skip to content

Instantly share code, notes, and snippets.

@jcward
Last active January 17, 2024 04:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcward/6ff13bceaea25ac4b4b5d2474f72aa01 to your computer and use it in GitHub Desktop.
Save jcward/6ff13bceaea25ac4b4b5d2474f72aa01 to your computer and use it in GitHub Desktop.
A Quick Haxe Client / Server Socket Example

A quick / simple example socket server and client

Requires Haxe and the cpp haxelib

Compile the server with:

haxe -cpp server -main Server

Compile the client with:

haxe -cpp client -main Client

Start the server:

./server/Server

In another terminal, run the client, e.g. targetting the localhost:

./client/Client 127.0.0.1

Observe the message passed from Server to Client

client_server.mp4

Related reading:

import sys.net.Host;
import sys.net.Socket;
class Client
{
public function new()
{
var args = Sys.args();
if (args.length==0) {
trace('Usage: Client <server ip / hostname>');
Sys.exit(1);
return;
}
var server = args[0];
trace('Connecting to ${ server }:8112');
var client = new Socket();
try {
client.connect(new Host(server), 8112);
} catch (e:Dynamic) {
trace('Failed to connect. Goodbye.');
Sys.exit(2);
}
var len = client.input.readInt32();
var val = client.input.readString(len);
trace('Server said: $val');
client.close();
trace('Closed socket. Goodbye!');
}
public static function main() new Client();
}
import sys.net.Socket;
class Server
{
public function new()
{
trace('Listening on 0.0.0.0:8112');
var listener = new Socket();
listener.bind(new sys.net.Host("0.0.0.0"), 8112);
listener.listen(8);
while (true) {
var socket : Socket = listener.accept(); // This line waits...
var msg = "Hello world!";
trace('Got connection, writing: $msg');
socket.output.writeInt32(msg.length);
socket.output.writeString(msg);
socket.close();
trace("Closed, will wait for next connection...");
}
}
public static function main() new Server();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment