Sunday, April 20, 2025

Sockets with Python - 2 - Sending Custom Headers

import socket 

msg = "Meeting at 14h, Office 279"

#Local IP Data

host = "192.168.0.103"
port = 54321

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Preparing for Connection")
s.bind((host, port))

print("Server Listening")
s.listen(5)

while True:
    conn, addr = s.accept()
    print("Connection From: ", addr)
    print("Sending Message: ")
    conn.sendall(msg.encode())
    conn.send(b"\r\n")
    conn.send(b"-----------------------")
    conn.send(b"\r\n")

This script creates a simple TCP server using the Python socket library. The server is set to listen on a specific IP address and port. When a client connects to the server, the server sends a message to the client.

The first three lines of the script define some variables: msg is the message that the server will send to clients, host is the IP address that the server will listen on, and port is the port number that the server will listen on.

The next line creates a new socket object using the socket.socket() method. The two arguments that are passed to this method specify that we are creating an IPv4 socket using the TCP protocol.

After creating the socket object, the script binds the socket to the host and port that we defined earlier using the s.bind() method.

Next, the script starts the server listening for incoming connections using the s.listen() method. The argument passed to this method specifies the maximum number of queued connections.

The next section of the script starts an infinite loop that will run until the server is stopped. Within the loop, the script waits for an incoming connection using the s.accept() method. When a connection is received, the method returns two values: a new socket object representing the connection, and the address of the client that made the connection.

Once a connection is established, the server sends the message defined in msg to the client using the conn.sendall() method. This method sends the message as a byte string, so the msg variable is first encoded using the encode() method.

Finally, the server sends a couple of newline characters and a line of dashes to the client to separate the message from any subsequent messages that might be sent. The conn.send() method is used to send these additional messages.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...