Beyond C/C++
API-ul de sockets este o o abstractizare foarte răspândită. Practic majoritatea interacțiunilor cu Internetul o să fie prin intermediul API-ul de sockets din sistemul de operare. Spre exemplu, orice implică networking în Python funcționează peste o abstractizare de sockets din limbaj care cheamă apelurile de sistem de sockets. În codul de mai jos putem vedea un astfel de exemplu.
import socket
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
msgFromServer = "Hello UDP Client"
bytesToSend = str.encode(msgFromServer)
# Create a datagram socket
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Bind to address and ip
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
# Listen for incoming datagrams
while(True):
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
clientMsg = "Message from Client:{}".format(message)
clientIP = "Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)
# Sending a reply to client
UDPServerSocket.sendto(bytesToSend, address)
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class udpBaseServer_2
{
public static void main(String[] args) throws IOException
{
// Step 1 : Create a socket to listen at port 1234
DatagramSocket ds = new DatagramSocket(1234);
byte[] receive = new byte[65535];
DatagramPacket DpReceive = null;
while (true)
{
// Step 2 : create a DatgramPacket to receive the data.
DpReceive = new DatagramPacket(receive, receive.length);
// Step 3 : revieve the data in byte buffer.
ds.receive(DpReceive);
System.out.println("Client:-" + data(receive));
// Exit the server if the client sends "bye"
if (data(receive).toString().equals("bye"))
{
System.out.println("Client sent bye.....EXITING");
break;
}
// Clear the buffer after every message.
receive = new byte[65535];
}
}
// A utility method to convert the byte array
// data into a string representation.
public static StringBuilder data(byte[] a)
{
if (a == null)
return null;
StringBuilder ret = new StringBuilder();
int i = 0;
while (a[i] != 0)
{
ret.append((char) a[i]);
i++;
}
return ret;
}
}
package main
import (
"fmt"
"log"
"net"
"time"
)
func main() {
// listen to incoming udp packets
udpServer, err := net.ListenPacket("udp", ":1053")
if err != nil {
log.Fatal(err)
}
defer udpServer.Close()
for {
buf := make([]byte, 1024)
_, addr, err := udpServer.ReadFrom(buf)
if err != nil {
continue
}
go response(udpServer, addr, buf)
}
}
func response(udpServer net.PacketConn, addr net.Addr, buf []byte) {
time := time.Now().Format(time.ANSIC)
responseStr := fmt.Sprintf("time received: %v. Your message: %v!", time, string(buf))
udpServer.WriteTo([]byte(responseStr), addr)
}