Sockets: Difference between revisions

31,765 bytes added ,  2 months ago
m
→‎{{header|Frink}}: Fixed port number
(Update for Boost 1.67+/Networking TS)
m (→‎{{header|Frink}}: Fixed port number)
 
(31 intermediate revisions by 21 users not shown)
Line 7:
=={{header|Ada}}==
{{libheader|GNAT RTL}}
<langsyntaxhighlight lang="ada">with GNAT.Sockets; use GNAT.Sockets;
 
procedure Socket_Send is
Line 20:
String'Write (Stream (Client), "hello socket world");
Close_Socket (Client);
end Socket_Send;</langsyntaxhighlight>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">file i, o;
tcpip_connect(i, o, "127.0.0.1", 256, 0);
i.text("hello socket world");</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">socket: connect.to:"localhost" 256
send socket "Hello Socket World"
unplug socket</syntaxhighlight>
 
=={{header|AutoHotkey}}==
modified from
[http://www.autohotkey.com/forum/topic13829.html script] by zed gecko.
<langsyntaxhighlight lang="autohotkey">Network_Port = 256
Network_Address = 127.0.0.1
NewData := false
Line 149 ⟶ 159:
ExitSub:
DllCall("Ws2_32\WSACleanup")
ExitApp</langsyntaxhighlight>
 
=={{header|AutoIt}}==
 
<langsyntaxhighlight AutoItlang="autoit">Func _HelloWorldSocket()
TCPStartup()
$Socket = TCPConnect("127.0.0.1", 256)
Line 159 ⟶ 169:
TCPCloseSocket($Socket)
TCPShutdown()
EndFunc</langsyntaxhighlight>
 
=={{header|AWK}}==
{{works with|GAWK}}
Note: <code>|&</code> is gawk's two way pipe operator.
 
Server:
<syntaxhighlight lang="awk">BEGIN {
s="/inet/tcp/256/0/0"
print strftime() |& s
close(s)
}
</syntaxhighlight>
 
Test client:
<syntaxhighlight lang="awk">BEGIN {
s="/inet/tcp/0/localhost/256"
s |& getline
print $0
close(s)
}</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SOCKLIB"
PROC_initsockets
Line 174 ⟶ 204:
PROC_closesocket(socket%)
PROC_exitsockets</langsyntaxhighlight>
 
=={{header|C}}==
Line 183 ⟶ 213:
With little changes it could work on MS Windows (without Cygwin) too. But I don't know exactly how. I have tested it using <code>nc -l -p 256</code>.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
 
const char *msg = "hello socket world";
Line 219 ⟶ 250:
freeaddrinfo(addrs);
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
I have tested it using <code>nc -vlp 4321</code>.
 
<lang cpp>//compile with g++ main.cpp -lboost_system -pthread
 
#include <boost/asio.hpp>
 
int main()
{
boost::asio::io_context io_context;
boost::asio::ip::tcp::socket sock(io_context);
boost::asio::ip::tcp::resolver resolver(io_context);
boost::asio::ip::tcp::resolver::query query("localhost", "4321");
 
boost::asio::connect(sock, resolver.resolve(query));
boost::asio::write(sock, boost::asio::buffer("Hello world socket\r\n"));
 
return 0;
}</lang>
 
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
using System.Net.Sockets;
Line 257 ⟶ 268:
tcp.Close();
}
}</langsyntaxhighlight>
 
Clean Socket alternative:
 
<langsyntaxhighlight lang="csharp">using System.Text;
using System.Net.Sockets;
 
Line 276 ⟶ 287:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
I have tested it using <code>nc -vlp 4321</code>.
 
<syntaxhighlight lang="cpp">//compile with g++ main.cpp -lboost_system -pthread
 
#include <boost/asio.hpp>
 
int main()
{
boost::asio::io_context io_context;
boost::asio::ip::tcp::socket sock(io_context);
boost::asio::ip::tcp::resolver resolver(io_context);
boost::asio::ip::tcp::resolver::query query("localhost", "4321");
 
boost::asio::connect(sock, resolver.resolve(query));
boost::asio::write(sock, boost::asio::buffer("Hello world socket\r\n"));
 
return 0;
}</syntaxhighlight>
 
=={{header|Cind}}==
 
<syntaxhighlight lang="cind">
var libsocket = @("lib","socket");
// connect
int socket = libsocket.connect("localhost",256);
// send data
{
sheet data = (sheet)"hello socket world";
int datalen = data.size();
int was = libsocket.send(socket,data,0,datalen);
// assuming here that all data has been sent (if not, send them in some loop)
}
// close socket
libsocket.close(socket);
</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns socket-example
(:import (java.net Socket)
(java.io PrintWriter)))
Line 288 ⟶ 336:
(.println printer msg)))
(send-data "localhost" "hello socket world")</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 294 ⟶ 342:
{{libheader|usocket}}
 
<langsyntaxhighlight lang="lisp">CL-USER> (usocket:with-client-socket (socket stream "localhost" 256)
(write-line "hello socket world" stream)
(values))
; No value</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">aurora ~% sudo nc -l -p 256
hello socket world</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">module socket ;
import std.stdio ;
import std.socket ;
Line 317 ⟶ 365:
writefln("Socket %d bytes sent.", res) ;
socket.close() ;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program Sockets;
 
{$APPTYPE CONSOLE}
Line 338 ⟶ 386:
lTCPClient.Free;
end;
end.</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 3.4.1 :
<langsyntaxhighlight lang="elena">import system'net.;
import system'text.;
import extensions'text.;
import system'io.;
public program()
{
[
var socket := Socket new Socket(AF_INET,SOCK_STREAM,IPPROTO_TCP).;
socket .connect("127.0.0.1",256).;
socketvar s write(AnsiEncoder:= toByteArray("hello socket world")).;
socket.write(AnsiEncoder.toByteArray(0, closes.Length, s));
socket.close()
]</lang>
}</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule Sockets do
require Logger
Line 366 ⟶ 416:
 
Sockets.send_message(256, "hello socket world")
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
Line 372 ⟶ 422:
Emacs treats network connections as sub-processes. <code>make-network-process</code> is the low-level socket creation,
 
<langsyntaxhighlight Lisplang="lisp">(let ((proc (make-network-process :name "my sock"
:host 'local ;; or hostname string
:service 256)))
(process-send-string proc "hello socket world")
(delete-process proc))</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(socket).
-export([start/0]).
 
Line 387 ⟶ 437:
ok = gen_tcp:send(Sock, "hello socket world"),
ok = gen_tcp:close(Sock).
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">"localhost" 256 <inet> utf8 [ "hello socket world" print ] with-client</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
using inet
 
Line 409 ⟶ 459:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{works with|GNU Forth|0.7.0}}
<langsyntaxhighlight lang="forth">include unix/socket.fs
 
s" localhost" 256 open-socket
Line 419 ⟶ 469:
dup s" hello socket world" rot write-socket
 
close-socket</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{libheader|winsock}}
{{works with|Windows FreeBASIC}}
<syntaxhighlight lang="vbnet">' We import the windows sockets library
#Include Once "windows.bi"
#Include Once "win/winsock.bi"
 
#include "fbgfx.bi"
 
#define NET_BUFLEN 1024
 
'--- SENDER ---
 
Dim As WSADATA wsaData
 
Dim As SOCKET sendSocket
Dim As sockaddr_in recvAddr
Dim As Integer port = 256
Dim As Ubyte sendBuf(NET_BUFLEN-1)
Dim As Integer bufLen = NET_BUFLEN
Dim As Integer iResult
Dim As String message = "hello socket world"
 
' We copy the message to the buffer
For i As Ubyte = 1 To Len(message)
sendBuf(i-1) = Cbyte(Asc(Mid(message, i, 1)))
Next
 
' We update bufLen to be the length of the message
bufLen = Len(message)
 
' We initialize Winsock
If (WSAStartup(MAKEWORD(2,2), @wsaData) <> 0) Then
Beep: Print "Error: Winsock init"
Sleep
End
End If
 
' We create the socket
sendSocket = socket_(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
If sendSocket = INVALID_SOCKET Then
Beep: Print "Error: Net socket"
WSACleanup()
Sleep
End
End If
 
' We configure the server structure
recvAddr.sin_family = AF_INET
recvAddr.sin_port = htons(256)
recvAddr.sin_addr.s_addr = inet_addr("127.0.0.1")
 
' We send the message
Print "Trying: Net send"
iResult = sendto(sendSocket, @sendBuf(0), bufLen, 0, Cptr(sockaddr Ptr, @recvAddr), Sizeof(recvAddr))
If (iResult = SOCKET_ERROR) Then
Beep: Print "Error: Net send"
closesocket(sendSocket)
WSACleanup()
Sleep
End
Else
Print "number of bytes send:"; iResult
End If
 
iResult = closeSocket(sendSocket)
If (iResult < 0) Then
Beep: Print "Error: Close socket"
End If
 
'closesocket(sock)
WSACleanup()</syntaxhighlight>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">s = newJava["java.net.Socket", ["localhost", 256]]
w = new Writer[s.getOutputStream[]]
w.println["hello socket world"]
w.close[]</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
import (
Line 440 ⟶ 569:
fmt.Println(err)
}
}</langsyntaxhighlight>
{{out | Test with nc}}
<pre>
Line 450 ⟶ 579:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">s = new java.net.Socket("localhost", 256)
s << "hello socket world"
s.close()</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Network
 
main = withSocketsDo $ sendTo "localhost" (PortNumber $ toEnum 256) "hello socket world"</langsyntaxhighlight>
 
== Icon and Unicon ==
==={{header|Icon}}===
<langsyntaxhighlight lang="icon">link cfunc
procedure main ()
hello("localhost", 1024)
Line 468 ⟶ 597:
procedure hello (host, port)
write(tconnect(host, port) | stop("unable to connect to", host, ":", port) , "hello socket world")
end</langsyntaxhighlight>
Note: Socket support in native Icon is limited and requires the external helper function cfunc.
==={{header|Unicon}}===
Unicon integrated TCP/IP networking and messaging.
<langsyntaxhighlight lang="unicon">procedure main(arglist) #: usage socket port hostname or socket port
hello(arglist[2]|"",arglist[1])
end
Line 487 ⟶ 616:
else stop("Unable to connect to ",host,":",port)
return
end</langsyntaxhighlight>
 
=={{header|IDL}}==
 
<langsyntaxhighlight lang="idl">socket, unit, 'localhost',256,/get_lun
printf,unit,"hello socket world"
close, unit</langsyntaxhighlight>
 
"Well-known" port numbers (under 1024 -- such as 256) can also be specified by name (in this case 'RAP').
Line 502 ⟶ 631:
<code>sdcheck</code> raises assertions if anything goes wrong:
 
<langsyntaxhighlight lang="j"> coinsert'jsocket' [ require 'socket' NB. Sockets library
socket =. >{.sdcheck sdsocket'' NB. Open a socket
host =. sdcheck sdgethostbyname 'localhost' NB. Resolve host
sdcheck sdconnect socket ; host ,< 256 NB. Create connection to port 256
sdcheck 'hello socket world' sdsend socket , 0 NB. Send msg</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.IOException;
import java.net.*;
public class SocketSend {
Line 522 ⟶ 651:
sock.close();
}
}</langsyntaxhighlight>
Encapsulating the <code>Socket</code>'s <code>OutputStream</code> in a <code>PrintStream</code> (for data) or <code>PrintWriter</code> (for text) may be easier in more complex programs for their auto-flush abilities, encoding management, and their overloaded <code>print</code> and <code>println</code> methods. The <code>write</code> method from the original <code>OutputStream</code> will still be available.
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
function sockets() {
var sock = new Socket({client:true, port:256, noAsync:true, udp:true});
sock.send(-1, 'hello socket world');
sock.close();
}
 
;sockets();
 
/*
=!EXPECTSTART!=
sockets() ==> undefined
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u sockets.jsi
[PASS] sockets.jsi</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
socket = connect("localhost",256)
write(socket, "hello socket world")
close(socket)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.21
 
import java.net.Socket
Line 542 ⟶ 691:
it.outputStream.write("hello socket world".toByteArray())
}
}</langsyntaxhighlight>
 
=={{header|Lasso}}==
 
<langsyntaxhighlight Lassolang="lasso">local(net) = net_tcp
#net->connect('127.0.0.1',256)
#net->dowithclose => {
#net->writestring('Hello World')
}</langsyntaxhighlight>
 
 
=={{header|Lua}}==
{{libheader|LuaSocket}}
<langsyntaxhighlight lang="lua">socket = require "socket"
host, port = "127.0.0.1", 256
 
sid = socket.udp()
sid:sendto( "hello socket world", host, port )
sid:close()</langsyntaxhighlight>
 
=={{header|MACRO-10}}==
<syntaxhighlight lang="macro-10">
 
TITLE SOCKET
 
COMMENT !
 
Socket Example ** PDP-10 Assembly Language (KJX 2022)
Assembler: MACRO-10 Operating System: TOPS-20 V7
 
On TOPS-20, TCP-connections are made by opening a special
file on the "TCP:" device (in this case "TCP:256"). Apart
from the funky filename, there is virtually no difference
between opening files on disk and creating TCP-connections
or endpoints, so we go through the usual sequence of GTJFN
(= get file-handle), OPENF (open file), finally followed
by CLOSF (close file).
 
!
 
SEARCH MONSYM,MACSYM ;Load symbolic names for syscalls.
.REQUIRE SYS:MACREL
 
STDAC. ;Define standard register names.
 
JFN: BLOCK 1 ;File handle for TCP connection.
TCPFN: ASCIZ /TCP:256/ ;TCP "filename"
STR: ASCIZ /Hello World!/ ;String to send.
STRLEN= <.-STR>*5 ;Length of string.
 
GO:: RESET% ;Initialize process.
 
;; Get a file-handle (JFN) for the TCP-connection:
MOVX T1,GJ%SHT ;Do "short" GTJFN% call.
HRROI T2,TCPFN ;TCP "filename" into T2.
GTJFN% ;Get file-handle.
ERJMPS ERROR ; Handle errors.
MOVEM T1,JFN ;Store JFN we got.
 
;; Open the "file":
 
HRRZ T1,JFN ;File-handle without flags into T1.
MOVX T2,FLD(8,OF%BSZ)!OF%RD!OF%WR ;8bit bytes, read+write.
OPENF% ;Open file.
ERJMPS ERROR ; Handle errors.
 
;; Write the string.
 
MOVE T1,JFN ;File-handle into T1.
HRROI T2,STR ;String-pointer into T2.
MOVEI T3,STRLEN ;Length of string into T3.
SOUT% ;Write string.
ERJMPS ERROR ; Handle errors.
 
;; Close file.
 
HRRZ T1,JFN ;Get file-handle into T1.
CLOSF% ;Close file.
ERJMPS ERROR ; Handle errors.
 
;; End program.
 
RESET% ;Reset, to release JFN.
HALTF% ;Halt program.
JRST GO ;Allow for continue-command.
 
;;
;; ERROR: Print standardized error-message by means of ERSTR.
;; This is similar to perror() in C.
;;
 
ERROR: MOVEI T1,.PRIOU ;Print on standard output.
MOVE T2,[.FHSLF,,-1] ;Own process, last error.
SETZ T3 ;No length-limit on error msg.
ERSTR% ;Print error-message.
JFCL ; Ignore errors from ERSTR%.
JFCL ; Dito.
RESET% ;Reset, to release JFN.
HALTF% ;Halt program.
JRST GO ;Allow for continue-command.
 
END GO
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">socket = SocketConnect["localhost:256", "TCP"];
WriteString[socket, "hello socket world"];
Close[socket];</syntaxhighlight>
 
=={{header|Myrddin}}==
<langsyntaxhighlight lang="myrddin">use std
 
const main = {
Line 573 ⟶ 811:
std.fatal("could not open fd: {}\n", err)
;;
}</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">import Nanoquery.Net
 
p = new(Port)
p.connect("localhost", 256)
p.write("hello socket world")
p.close()</syntaxhighlight>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
Sockets in Neko
Tectonics:
Line 599 ⟶ 845:
socket_write(socket, "hello socket world");
 
socket_close(socket);</langsyntaxhighlight>
 
For testing on port 256, root powers required
Line 613 ⟶ 859:
 
=={{header|Nemerle}}==
<langsyntaxhighlight lang="nemerle">using System.Text;
using System.Net.Sockets;
 
Line 625 ⟶ 871:
sock.Close();
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|Java}}
<<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
import java.net.
Line 657 ⟶ 903:
end
return
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="newlisp">
(set 'socket (net-connect "localhost" 256))
(net-send socket "hello socket world")
(net-close socket)
(exit)
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import net
 
var s = newSocket()
s.connect("localhost", Port(256))
s.send("Hello Socket World")
s.close()</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use Net;
 
Line 690 ⟶ 936:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
(untested)
<langsyntaxhighlight lang="objc">// declare the class to conform to NSStreamDelegate protocol
 
// in some method
Line 713 ⟶ 959:
[oStream close];
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">open Unix
 
let init_socket addr port =
Line 727 ⟶ 973:
let outchan = out_channel_of_descr sock in
let inchan = in_channel_of_descr sock in
(inchan, outchan)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ocaml">let () =
let ic, oc = init_socket "localhost" 256 in
output_string oc "hello socket world";
;;</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
Socket = {New Open.socket init}
in
{Socket connect(port:256)}
{Socket write(vs:"hello socket world")}
{Socket close}</langsyntaxhighlight>
 
=={{header|Pascal}}==
Tested using <code>nc -l 256</code>, on both macOS Sierra and Windows 7, compiled using Free Pascal in the default FPC mode.
See [[Sockets#Delphi | Delphi]]
Very similar to the [https://rosettacode.org/wiki/Sockets#C example in C].
 
See also [https://rosettacode.org/wiki/Sockets#Delphi Delphi].
<syntaxhighlight lang="pascal">Program Sockets_ExampleA;
 
Uses
{ Free Pascal RTL sockets unit }
sockets;
 
Var
TCP_Sock: integer;
Remote_Addr: TSockAddr;
 
Message: string;
PMessage: Pchar;
Message_Len: integer;
 
 
Begin
{ Fill the record (struct) with the server's address information }
With Remote_Addr do
begin
Sin_family := AF_INET;
Sin_addr := StrToNetAddr('127.0.0.1');
Sin_port := HtoNs(256);
end;
 
{ Returns an IPv4 TCP socket descriptor }
TCP_Sock := fpSocket(AF_INET, SOCK_STREAM, IPPROTO_IP);
 
{ Most routines in this unit return -1 on failure }
If TCP_Sock = -1 then
begin
WriteLn('Failed to create new socket descriptor');
Halt(1);
end;
 
{ Attempt to connect to the address supplied above }
If fpConnect(TCP_Sock, @Remote_Addr, SizeOf(Remote_Addr)) = -1 then
begin
{ Specifc error codes can be retrieved by calling the SocketError function }
WriteLn('Failed to contact server');
Halt(1);
end;
 
{ Finally, send the message to the server and disconnect }
Message := 'Hello socket world';
PMessage := @Message;
Message_Len := StrLen(PMessage);
 
If fpSend(TCP_Sock, PMessage, Message_Len, 0) <> Message_Len then
begin
WriteLn('An error occurred while sending data to the server');
Halt(1);
end;
 
CloseSocket(TCP_Sock);
End.
</syntaxhighlight>
 
Variant without superfluous additions:
<syntaxhighlight lang="pascal">Program Sockets_ExampleB;
 
Uses
sockets;
 
Var
TCP_Sock: integer;
Remote_Addr: TSockAddr;
 
Message: string;
PMessage: Pchar;
Message_Len: integer;
 
Begin
Remote_Addr.Sin_family := AF_INET;
Remote_Addr.Sin_addr := StrToNetAddr('127.0.0.1');
Remote_Addr.Sin_port := HtoNs(256);
 
TCP_Sock := fpSocket(AF_INET, SOCK_STREAM, IPPROTO_IP);
 
fpConnect(TCP_Sock, @Remote_Addr, SizeOf(Remote_Addr));
 
Message := 'Hello socket world';
PMessage := @Message;
Message_Len := StrLen(PMessage);
 
fpSend(TCP_Sock, PMessage, Message_Len, 0);
End.
</syntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Socket;
 
$host = gethostbyname('localhost');
Line 754 ⟶ 1,090:
connect(Socket_Handle, $in);
send(Socket_Handle, 'hello socket world', 0, $in);
close(Socket_Handle);</langsyntaxhighlight>
 
Object oriented version.
<langsyntaxhighlight lang="perl">use Socket::Class;
 
$sock = Socket::Class->new(
Line 763 ⟶ 1,099:
) || die Socket::Class->error;
$sock->send('hello socket world');
$sock->free;</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
Note this fails for me with "connection refused", just like the Go/Python/Ruby entries.
{{Works with|rakudo|2016.03}}
<!--<syntaxhighlight lang="phix">(notonline)-->
Will fail with a connect error if there is not a socket server of some kind available on the specified host and port.
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (sockets)</span>
<lang perl6>my $host = '127.0.0.1';
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">sockets</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
my $port = 256;
<span style="color: #008080;">constant</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"hello socket world"</span>
 
<span style="color: #004080;">atom</span> <span style="color: #000000;">sock</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">socket</span><span style="color: #0000FF;">(</span><span style="color: #000000;">AF_INET</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">SOCK_STREAM</span><span style="color: #0000FF;">)</span>
my $client = IO::Socket::INET.new(:$host, :$port);
<span style="color: #008080;">if</span> <span style="color: #000000;">sock</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
$client.print( 'hello socket world' );
<span style="color: #004080;">atom</span> <span style="color: #000000;">pSockAddr</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sockaddr_in</span><span style="color: #0000FF;">(</span><span style="color: #000000;">AF_INET</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"localhost"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">256</span><span style="color: #0000FF;">)</span>
$client.close;</lang>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">connect</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sock</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pSockAddr</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SOCKET_ERROR</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"connect (%v)"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">get_socket_error</span><span style="color: #0000FF;">()})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">pm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">msg</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pm</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">slen</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">send</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sock</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pm</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">slen</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">slen</span><span style="color: #0000FF;">=</span><span style="color: #000000;">len</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">pm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pm</span><span style="color: #0000FF;">[</span><span style="color: #000000;">slen</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">closesocket</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sock</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">WSACleanup</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">$socket = fsockopen('localhost', 256);
fputs($socket, 'hello socket world');
fclose($socket);</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(when (connect "localhost" 256)
(out @ (prinl "hello socket world"))
(close @) )</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">import Stdio;
 
int main(){
Line 793 ⟶ 1,144:
con->write("hello socket world");
con->close();
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
This works with Gnu Prolog. Other implementations will have different predicates.
<langsyntaxhighlight Prologlang="prolog">start(Port) :- socket('AF_INET',Socket),
socket_connect(Socket, 'AF_INET'(localhost,Port), Input, Output),
write(Output, 'hello socket world'),
flush_output(Output),
close(Output),
close(Input).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight Purebasiclang="purebasic">InitNetwork()
ConnectionID = OpenNetworkConnection("localhost", 256)
SendNetworkString(ConnectionID, "hello socket world")
CloseNetworkConnection(ConnectionID)</langsyntaxhighlight>
 
=={{header|Python}}==
<syntaxhighlight lang ="python">import socket
"""Connect to a socket. Requires Python >= 3.2."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
import socket
sock.connect(("localhost", 256))
 
sock.sendall("hello socket world")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.close()</lang>
sock.connect(("localhost", 256))
sock.sendall(b"hello socket world")
</syntaxhighlight>
 
{{out}}
 
This example output uses netcat (<code>nc</code>) to provide a socket to connect to. Some versions of netcat require the <code>-p</code> (port) flag to be used in combination with <code>-l</code> (listen mode), some treat the combination of <code>-l</code> and <code>-p</code> as an error, and some don't mind either way. On some systems, you can use <code>sudo netstat -tulpn | grep nc</code> to show what port netcat is actually listening on.
 
256 is a "well-known", reserved port number. Binding to well-known ports usually requires elevated permissions. Hence the use of <code>sudo</code> here.
<pre>
$ sudo nc -l -p 256 & python sock.py
[3] 10559
hello socket world[3] Done sudo nc -l -p 256
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="rsplus">
s <- make.socket(port = 256)
write.socket(s, "hello socket world")
close.socket(s)
</syntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(let-values ([(in out) (tcp-connect "localhost" 256)])
(display "hello socket world\n" out)
(close-output-port out))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2016.03}}
Will fail with a connect error if there is not a socket server of some kind available on the specified host and port.
<syntaxhighlight lang="raku" line>my $host = '127.0.0.1';
my $port = 256;
 
my $client = IO::Socket::INET.new(:$host, :$port);
$client.print( 'hello socket world' );
$client.close;</syntaxhighlight>
 
=={{header|Rhope}}==
{{works with|Rhope|alpha 1}}
<langsyntaxhighlight lang="rhope">Socket Send(0,0)
|:
[New@Net Client["localhost",256]]Put String["hello socket world"]
:|</langsyntaxhighlight>
The connection is automatically closed when the object is freed.
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Load "guilib.ring"
 
Line 872 ⟶ 1,256:
waitforbyteswritten(300000)
close()
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'socket'
sock = TCPSocket.open("localhost", 256)
sock.write("hello socket world")
sock.close</langsyntaxhighlight>
 
=={{header|Rust}}==
{{works with|Rust 1.0 stable}}
<langsyntaxhighlight lang="rust">use std::io::prelude::*;
use std::net::TcpStream;
 
Line 892 ⟶ 1,276:
let _ = my_stream.write(b"hello socket world");
 
} // <- my_stream's drop function gets called, which closes the socket</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import java.net.Socket
 
object sendSocketData {
Line 908 ⟶ 1,292:
 
sendData("localhost", "hello socket world")
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Guile|1.8.8}}{{works with|Chicken Scheme|4.6.0}}
<langsyntaxhighlight lang="scheme">(let ((s (socket PF_INET SOCK_STREAM 0)))
(connect s AF_INET (inet-pton AF_INET "127.0.0.1") 256)
(display "hello socket world" s))</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 921 ⟶ 1,305:
which returns a connected internet socket file at a port at localhost.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "socket.s7i";
 
Line 931 ⟶ 1,315:
writeln(sock, "hello socket world");
close(sock);
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">
set SocketID to "localhost:256"
open socket SocketID
write "Hello socket world!" to socket SocketID
close socket SocketID
</syntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var host = Socket.gethostbyname('localhost');
var in = Socket.sockaddr_in(256, host);
var proto = Socket.getprotobyname('tcp');
Line 941 ⟶ 1,333:
sock.connect(in);
sock.send('hello socket world', 0, in);
sock.close;</langsyntaxhighlight>
 
=={{header|Slate}}==
Line 947 ⟶ 1,339:
This uses fairly verbose and low level messages. This will probably be simplified in the future.
 
<langsyntaxhighlight lang="slate">[ | socket |
[ | addr stream |
addr: (Net SocketAddress newOn: '127.0.0.1:256').
Line 956 ⟶ 1,348:
stream flush
] ensure: [socket close]
] do.</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 963 ⟶ 1,355:
This is taken from [http://sblinn.jottit.com/GNU_Smalltalk_SimpleEcho_TCP_Server here] with few modification to fit the task better.
 
<langsyntaxhighlight lang="smalltalk">PackageLoader fileInPackage: 'TCP'!
 
Object subclass: #HelloSocket
Line 1,001 ⟶ 1,393:
 
handleSocket: s
| msg |/**
Sockets in Neko
Tectonics:
nekoc sockets.neko
sudo nc -vulp 256 & sudo neko sockets
*/
 
var socket_init = $loader.loadprim("std@socket_init", 0);
var socket_new = $loader.loadprim("std@socket_new", 1);
var host_resolve = $loader.loadprim("std@host_resolve", 1);
var socket_connect = $loader.loadprim("std@socket_connect", 3);
var socket_write = $loader.loadprim("std@socket_write", 2);
var socket_close = $loader.loadprim("std@socket_close", 1);
 
/* Initialize Neko socket API */
socket_init();
 
/* true; UDP, false; TCP */
var socket = socket_new(true);
 
var c = socket_connect(socket, host_resolve("localhost"), 1256);
socket_write(socket, "hello socket world");
 
socket_close(socket);
msg := 'hello socket world'.
msg displayOn: s.
Line 1,033 ⟶ 1,402:
Smalltalk at: #helloServer put: (HelloSocket port: 2560).
 
helloServer run.</langsyntaxhighlight>
 
=={{header|Symsyn}}==
<langsyntaxhighlight lang="symsyn">
'127.0.0.1' $addr
connect $addr 256 sok
'hello socket world' [sok]
close sok
</syntaxhighlight>
</lang>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="text">val txt = Word8VectorSlice.full (Byte.stringToBytes "hello world" ) ;
val set = fn socket => fn ipnr => fn portnr => fn text =>
(
Socket.connect (socket, INetSock.toAddr ( Option.valOf (NetHostDB.fromString(ipnr) ) , portnr )) ;
Socket.sendVec(socket, text) before Socket.close socket
)
;
</syntaxhighlight>
call
set ( INetSock.TCP.socket () ) "127.0.0.1" 256 txt ;
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set io [socket localhost 256]
puts -nonewline $io "hello socket world"
close $io</langsyntaxhighlight>
 
=={{header|Toka}}==
<langsyntaxhighlight lang="toka">needs sockets
 
#! A simple abstraction layer that makes writing trivial servers easy
Line 1,062 ⟶ 1,442:
 
#! The actual server
[ " hello socket world" server.send ] 256 server.start</langsyntaxhighlight>
 
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txrlisp">(let* ((server (first (getaddrinfo "localhost" 256)))
(sock (open-socket server.family sock-stream)))
(sock-connect sock server)
(put-string "hello socket world"))</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 1,075 ⟶ 1,455:
 
{{libheader|nc}}
<langsyntaxhighlight lang="bash">echo "hello socket world" | nc localhost 256</langsyntaxhighlight>
 
When the connection fails, <code>nc</code> exits 1. To see an error message, use <code>nc -v localhost 256</code>.
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl port p
p.connect "localhost" 256
out "hello socket world" endl p
p.close</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
<langsyntaxhighlight lang="vbnet">Imports System
Imports System.IO
Imports System.Net.Sockets
Line 1,101 ⟶ 1,481:
tcp.Close()
End Sub
End Class</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|C}}
An embedded program so we can ask the C host to call the relevant library functions for us.
 
Although this worked when originally posted, the connection is now refused. The same applies to the C, Go, Phix, Python and Ruby entries and probably others.
<syntaxhighlight lang="wren">/* Sockets.wren */
 
var AF_UNSPEC = 0
var SOCK_STREAM = 1
 
foreign class AddrInfo {
foreign static getAddrInfo(name, service, req, pai)
 
construct new() {}
 
foreign family
 
foreign family=(f)
 
foreign sockType
 
foreign sockType=(st)
 
foreign protocol
 
foreign addr
 
foreign addrLen
}
 
foreign class AddrInfoPtr {
construct new() {}
 
foreign deref
 
foreign free()
}
 
foreign class SockAddrPtr {
construct new() {}
}
 
class Socket {
foreign static create(domain, type, protocol)
 
foreign static connect(fd, addr, len)
 
foreign static send(fd, buf, n, flags)
 
foreign static close(fd)
}
 
var msg = "hello socket world\n"
var hints = AddrInfo.new()
hints.family = AF_UNSPEC
hints.sockType = SOCK_STREAM
var addrInfoPtr = AddrInfoPtr.new()
if (AddrInfo.getAddrInfo("localhost", "256", hints, addrInfoPtr) == 0){
var addrs = addrInfoPtr.deref
var sock = Socket.create(addrs.family, addrs.sockType, addrs.protocol)
if (sock >= 0) {
var stat = Socket.connect(sock, addrs.addr, addrs.addrLen)
if (stat >= 0) {
var pm = msg
while (true) {
var len = pm.count
var slen = Socket.send(sock, pm, len, 0)
if (slen < 0 || slen >= len) break
pm = pm[slen..-1]
}
} else if (stat == -1) {
System.print("Connection refused.")
}
var status = Socket.close(sock)
if (status != 0) System.print("Failed to close socket.")
}
addrInfoPtr.free()
}</syntaxhighlight>
<br>
Now embed this script in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Sockets.c -o Sockets -lwren -lm */
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include "wren.h"
 
/* C <=> Wren interface functions */
 
void C_addrInfoAllocate(WrenVM* vm) {
wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct addrinfo));
}
 
void C_addrInfoPtrAllocate(WrenVM* vm) {
wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct addrinfo*));
}
 
void C_sockAddrPtrAllocate(WrenVM* vm) {
wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct sockaddr*));
}
 
void C_getAddrInfo(WrenVM* vm) {
const char *name = wrenGetSlotString(vm, 1);
const char *service = wrenGetSlotString(vm, 2);
const struct addrinfo *req = (const struct addrinfo *)wrenGetSlotForeign(vm, 3);
struct addrinfo** ppai = (struct addrinfo**)wrenGetSlotForeign(vm, 4);
int status = getaddrinfo(name, service, req, ppai);
wrenSetSlotDouble(vm, 0, (double)status);
}
 
void C_family(WrenVM* vm) {
struct addrinfo* pai = (struct addrinfo*)wrenGetSlotForeign(vm, 0);
wrenSetSlotDouble(vm, 0, (double)(pai->ai_family));
}
 
void C_setFamily(WrenVM* vm) {
struct addrinfo* pai = (struct addrinfo*)wrenGetSlotForeign(vm, 0);
int f = (int)wrenGetSlotDouble(vm, 1);
pai->ai_family = f;
}
 
void C_sockType(WrenVM* vm) {
struct addrinfo* pai = (struct addrinfo*)wrenGetSlotForeign(vm, 0);
wrenSetSlotDouble(vm, 0, (double)(pai->ai_socktype));
}
 
void C_setSockType(WrenVM* vm) {
struct addrinfo* pai = (struct addrinfo*)wrenGetSlotForeign(vm, 0);
int type = (int)wrenGetSlotDouble(vm, 1);
pai->ai_socktype = type;
}
 
void C_protocol(WrenVM* vm) {
struct addrinfo* pai = (struct addrinfo*)wrenGetSlotForeign(vm, 0);
wrenSetSlotDouble(vm, 0, (double)(pai->ai_protocol));
}
 
void C_addr(WrenVM* vm) {
wrenEnsureSlots(vm, 2);
struct addrinfo* pai = (struct addrinfo*)wrenGetSlotForeign(vm, 0);
wrenGetVariable(vm, "main", "SockAddrPtr", 1);
struct sockaddr **ppsa = (struct sockaddr**)wrenSetSlotNewForeign(vm, 0, 1, sizeof(struct sockaddr*));
*ppsa = pai->ai_addr;
}
 
void C_addrLen(WrenVM* vm) {
struct addrinfo* pai = (struct addrinfo*)wrenGetSlotForeign(vm, 0);
wrenSetSlotDouble(vm, 0, (double)(pai->ai_addrlen));
}
 
void C_deref(WrenVM* vm) {
wrenEnsureSlots(vm, 2);
struct addrinfo** ppai = (struct addrinfo**)wrenGetSlotForeign(vm, 0);
wrenGetVariable(vm, "main", "AddrInfo", 1);
struct addrinfo *pai = (struct addrinfo*)wrenSetSlotNewForeign(vm, 0, 1, sizeof(struct addrinfo));
*pai = **ppai;
}
 
void C_free(WrenVM* vm) {
struct addrinfo* pai = *(struct addrinfo**)wrenGetSlotForeign(vm, 0);
freeaddrinfo(pai);
}
 
void C_create(WrenVM* vm) {
int domain = (int)wrenGetSlotDouble(vm, 1);
int type = (int)wrenGetSlotDouble(vm, 2);
int protocol = (int)wrenGetSlotDouble(vm, 3);
int fd = socket(domain, type, protocol);
wrenSetSlotDouble(vm, 0, (double)fd);
}
 
void C_connect(WrenVM* vm) {
int fd = (int)wrenGetSlotDouble(vm, 1);
__CONST_SOCKADDR_ARG *psa = (__CONST_SOCKADDR_ARG *)wrenGetSlotForeign(vm, 2);
socklen_t len = (socklen_t)wrenGetSlotDouble(vm, 3);
int status = connect(fd, *psa, len);
wrenSetSlotDouble(vm, 0, (double)status);
}
 
void C_send(WrenVM* vm) {
int fd = (int)wrenGetSlotDouble(vm, 1);
const char *buf = (const char *)wrenGetSlotString(vm, 2);
size_t n = (size_t)wrenGetSlotDouble(vm, 3);
int flags = (int)wrenGetSlotDouble(vm, 4);
ssize_t size = send(fd, (const void*)buf, n, flags);
wrenSetSlotDouble(vm, 0, (double)size);
}
 
void C_close(WrenVM* vm) {
int fd = (int)wrenGetSlotDouble(vm, 1);
int status = close(fd);
wrenSetSlotDouble(vm, 0, (double)status);
}
 
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "AddrInfo") == 0) {
methods.allocate = C_addrInfoAllocate;
} else if (strcmp(className, "AddrInfoPtr") == 0) {
methods.allocate = C_addrInfoPtrAllocate;
} else if (strcmp(className, "SockAddPtr") == 0) {
methods.allocate = C_sockAddrPtrAllocate;
}
}
return methods;
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "AddrInfo") == 0) {
if ( isStatic && strcmp(signature, "getAddrInfo(_,_,_,_)") == 0) return C_getAddrInfo;
if (!isStatic && strcmp(signature, "family") == 0) return C_family;
if (!isStatic && strcmp(signature, "family=(_)") == 0) return C_setFamily;
if (!isStatic && strcmp(signature, "sockType") == 0) return C_sockType;
if (!isStatic && strcmp(signature, "sockType=(_)") == 0) return C_setSockType;
if (!isStatic && strcmp(signature, "protocol") == 0) return C_protocol;
if (!isStatic && strcmp(signature, "addr") == 0) return C_addr;
if (!isStatic && strcmp(signature, "addrLen") == 0) return C_addrLen;
} else if (strcmp(className, "AddrInfoPtr") == 0) {
if (!isStatic && strcmp(signature, "deref") == 0) return C_deref;
if (!isStatic && strcmp(signature, "free()") == 0) return C_free;
} else if (strcmp(className, "Socket") == 0) {
if ( isStatic && strcmp(signature, "create(_,_,_)") == 0) return C_create;
if ( isStatic && strcmp(signature, "connect(_,_,_)") == 0) return C_connect;
if ( isStatic && strcmp(signature, "send(_,_,_,_)") == 0) return C_send;
if ( isStatic && strcmp(signature, "close(_)") == 0) return C_close;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Sockets.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
{{out}}
<pre>
$ sudo nc -l 256 & ./Sockets
[23] 6074
Connection refused.
</pre>
 
=={{header|X86 Assembly}}==
{{works with|nasm|Linux}}
<langsyntaxhighlight lang="asm">
;using sockets on linux with the 0x80 inturrprets.
;
Line 1,269 ⟶ 1,955:
sport resb 2
buff resb 1024
</syntaxhighlight>
</lang>
 
{{works with|MASM}}<br>
Operates in non-blocking mode.
<langsyntaxhighlight lang="asm">
.586
.model flat,stdcall
Line 1,419 ⟶ 2,105:
 
end start
</syntaxhighlight>
</lang>
 
{{works with|MASM}}<br>
This example works in blocking mode.
<langsyntaxhighlight lang="asm">
.586
.model flat,stdcall
Line 1,542 ⟶ 2,228:
 
end start
</syntaxhighlight>
</lang>
 
=={{header|X86-64 Assembly}}==
===UASM 2.52===
<syntaxhighlight lang="asm">
option casemap:none
option literals:on
 
ifndef __SOCKET_CLASS__
__SOCKET_CLASS__ equ 1
if @Platform eq windows64
 
WSADATA struct
wVersion dw ?
wHighVersion dw ?
iMaxSockets dw ?
iMaxUdpDg dw ?
szDescription db 256 dup (?)
szSystemStatus db 128 dup (?)
lpVendorInfo dq ?
WSADATA ends
 
option dllimport:<kernel32>
ExitProcess proto :word
HeapAlloc proto :qword, :dword, :qword
HeapFree proto :qword, :dword, :qword
GetProcessHeap proto
 
option dllimport:<ws2_32>
WSAStartup proto :word, :qword
WSACleanup proto :qword
closesocket proto :dword
 
option dllimport:none
exit equ ExitProcess
close equ closesocket
 
elseif @Platform eq linux64
malloc proto SYSTEMV :qword
free proto SYSTEMV :qword
close proto SYSTEMV :dword
exit proto SYSTEMV :dword
 
endif
 
memset proto :qword, :dword, :dword
printf proto :qword, :vararg
strlen proto :qword
getaddrinfo proto :qword, :qword, :qword, :qword
gai_strerror proto :dword
send proto :dword, :qword, :qword, :dword
socket proto :dword, :dword, :dword
connect proto :dword, :qword, :dword
freeaddrinfo proto :qword
CLASS socket_class
CMETHOD conn
CMETHOD write
ENDMETHODS
if @Platform eq windows64
wsa WSADATA <?>
endif
sock dd 0
pai dq 0
hostname dq ?
port dq ?
ENDCLASS
 
METHOD socket_class, Init, <VOIDARG>, <>, h:qword, p:qword
mov rbx, thisPtr
assume rbx:ptr socket_class
mov rax, h
mov [rbx].hostname, rax
mov rax, p
mov [rbx].port, rax
mov rax, rbx
assume rbx:nothing
ret
ENDMETHOD
 
METHOD socket_class, conn, <dword>, <>
local ht:qword
 
mov rbx, thisPtr
assume rbx:ptr socket_class
invoke printf, CSTR("--> Attempting connection to %s on %s",10), [rbx].hostname ,[rbx].port
if @Platform eq windows64
invoke WSAStartup, 202h, addr [rbx].wsa
endif
invoke memset, ht, 0, 0x30 ;; sizeof(struct addrinfo)
mov rax, ht
mov dword ptr [rax], 0 ;; ai_flags
mov dword ptr [rax+4], AF_INET
mov dword ptr [rax+8], SOCK_STREAM
invoke getaddrinfo, [rbx].hostname, [rbx].port, ht, addr [rbx].pai
.if rax != 0
invoke gai_strerror, eax
invoke printf, CSTR("--> Gai_strerror returned: %s",10), rax
mov rax, -1
jmp _exit
.endif
mov rax, [rbx].pai
mov edx, dword ptr [rax + 0XC] ;; pai.ai_protocol
mov ecx, dword ptr [rax + 8] ;; pai.ai_socktype
mov eax, dword ptr [rax + 4] ;; pai.ai_family
invoke socket, eax, ecx, edx
.if rax == -1
mov rax, -1
jmp _exit
.endif
mov [rbx].sock, eax
invoke printf, CSTR("--> Socket created as: %d",10), [rbx].sock
mov rax, [rbx].pai
mov edx, dword ptr [rax + 0x10] ;; pai.ai_addrlen
mov rcx, qword ptr [rax + 0x18] ;; pai.ai_addr
invoke connect, [rbx].sock, rcx, edx
.if rax == -1
invoke printf, CSTR("--> connect failed.. %i",10), rax
mov rax, -1
jmp _exit
.endif
mov rax, 0
 
_exit:
assume rbx:nothing
ret
ENDMETHOD
 
METHOD socket_class, write, <dword>, <>, b:qword
local tmp:qword
 
mov rbx, thisPtr
assume rbx:ptr socket_class
mov rax, b
mov tmp, rax
invoke strlen, tmp
invoke send, [rbx].sock, tmp, rax, 0
.if eax == -1
invoke printf, CSTR("--> Error in send..%d",10), rax
ret
.endif
assume rbx:nothing
ret
ENDMETHOD
 
METHOD socket_class, Destroy, <VOIDARG>, <>
mov rbx, thisPtr
assume rbx:ptr socket_class
invoke close, [rbx].sock
if @Platform eq windows64
invoke WSACleanup, addr [rbx].wsa
endif
.if [rbx].pai != 0
invoke freeaddrinfo, [rbx].pai
.endif
assume rbx:nothing
ret
ENDMETHOD
endif ;; __SOCKET_CLASS__
 
.code
main proc
local lpSocket:ptr socket_class
 
mov lpSocket, _NEW(socket_class, CSTR("localhost"), CSTR("256"))
lpSocket->conn()
.if rax == -1
invoke exit, 0
ret
.endif
invoke printf, CSTR("-> Connected, sending data.",10)
lpSocket->write(CSTR("Goodbye, socket world!",10))
_DELETE(lpSocket)
invoke exit, 0
ret
main endp
 
end
 
</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var s=Network.TCPClientSocket.connectTo("localhost",256);
s.write("hello socket world"); //-->18
s.close();</langsyntaxhighlight>
 
=={{header|Zsh}}==
<langsyntaxhighlight lang="zsh">zmodload zsh/net/tcp
ztcp localhost 256
print hello socket world >&$REPLY</langsyntaxhighlight>
 
{{omit from|ACL2}}
Line 1,561 ⟶ 2,427:
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Locomotive Basic|Does not have network access.}}
{{omit from|Mathematica}}
{{omit from|Maxima}}
{{omit from|ML/I}}
490

edits