在本文中,我们将看到如何使用带Python的套接字编程来创建服务器和客户端聊天室系统。
套接字是任何通信通道的端点。这些用于连接服务器和客户端。套接字是双向的。在该区域中,我们将为每个端设置套接字,并通过服务器在不同客户端之间设置聊天室系统。服务器端有一些端口可与客户端套接字连接。当客户端尝试使用相同的端口连接时,将为聊天室建立连接。
基本上有两个部分。服务器端和客户端。服务器端脚本运行时,它将等待任何活动的连接请求。建立一个连接后,即可与其通信。
在这种情况下,我们使用本地主机。如果机器通过局域网连接,那么我们可以使用IP地址进行通信。服务器将显示其IP,并要求该服务器的名称。在客户端,我们必须提到一个名称,以及要连接的服务器的IP地址。
import time, socket, sys print('Setup Server...') time.sleep(1) #Get the hostname, IP Address from socket and set Port soc = socket.socket() host_name = socket.gethostname() ip = socket.gethostbyname(host_name) port = 1234 soc.bind((host_name, port)) print(host_name, '({})'.format(ip)) name = input('Enter name: ') soc.listen(1) #Try to locate using socket print('Waiting for incoming connections...') connection, addr = soc.accept() print("Received connection from ", addr[0], "(", addr[1], ")\n") print('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[0])) #get a connection from client side client_name = connection.recv(1024) client_name = client_name.decode() print(client_name + ' has connected.') print('Press [bye] to leave the chat room') connection.send(name.encode()) whileTrue: message = input('Me > ') if message == '[bye]': message = 'Good Night...' connection.send(message.encode()) print("\n") break connection.send(message.encode()) message = connection.recv(1024) message = message.decode() print(client_name, '>', message)
import time, socket, sys print('Client Server...') time.sleep(1) #Get the hostname, IP Address from socket and set Port soc = socket.socket() shost = socket.gethostname() ip = socket.gethostbyname(shost) #get information to connect with the server print(shost, '({})'.format(ip)) server_host = input('Enter server\'s IP address:') name = input('Enter Client\'s name: ') port = 1234 print('Trying to connect to the server: {}, ({})'.format(server_host, port)) time.sleep(1) soc.connect((server_host, port)) print("Connected...\n") soc.send(name.encode()) server_name = soc.recv(1024) server_name = server_name.decode() print('{} has joined...'.format(server_name)) print('Enter [bye] to exit.') whileTrue: message = soc.recv(1024) message = message.decode() print(server_name, ">", message) message = input(str("Me > ")) if message == "[bye]": message = "Leaving the Chat room" soc.send(message.encode()) print("\n") break soc.send(message.encode())