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()
conn, addr = s.accept()
print("Connection From: ", addr)
print("Sending Message: ")
conn.sendall(msg.encode())
This script sets up a TCP server that listens on a specific IP address and port for incoming connections. Once a client establishes a connection, it sends a message to the client.
Here is a step-by-step explanation of the code:
-
import socket
: This line imports the socket module which provides a way to communicate over the internet using TCP/IP. -
msg = "Meeting at 14h, Office 279"
: This line sets the message that will be sent to the client when the connection is established. -
host = "192.168.0.103"
: This line sets the IP address of the server. -
port = 54321
: This line sets the port number that the server will listen on. -
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
: This line creates a new socket object using the AF_INET address family (IPv4) and the SOCK_STREAM socket type (TCP). -
print("Preparing for Connection")
: This line prints a message to the console to indicate that the server is preparing to start. -
s.bind((host, port))
: This line binds the socket to the specified IP address and port number. -
print("Server Listening")
: This line prints a message to the console to indicate that the server is now listening for incoming connections. -
s.listen()
: This line sets the server to listen for incoming connections. Thelisten()
method takes one argument which specifies the maximum number of queued connections (backlog) that the server will allow. -
conn, addr = s.accept()
: This line waits for a client to connect to the server and accepts the connection. Theaccept()
method returns a tuple containing a new socket object (conn
) which can be used to send and receive data on the connection, and the address of the client (addr
) which consists of the client's IP address and port number. -
print("Connection From: ", addr)
: This line prints the address of the client that has connected to the server. -
print("Sending Message: ")
: This line prints a message to the console to indicate that the server is about to send the message to the client. -
conn.sendall(msg.encode())
: This line sends the message to the client using thesendall()
method of the socket object (conn
). Theencode()
method is used to convert the message string into bytes, which is required when sending data over the network.
Overall, this script sets up a simple TCP server that listens for incoming connections and sends a message to the client once the connection is established.
No comments:
Post a Comment