编写一个基于TCP协议的网络通信程序,一个客户程序,一个服务器程序。要求服务器通过socket连接后,接收客户端传来的用户名,判断为“liu”时,向客户端发送字符串“Hello,You are connected!”,否则,发送字符串“Sorry,you are not the user!”。客户端通过键盘输入用户名,发送到服务器,接收服务器发来的信息输出后结束。服务端显示客户端的IP地址。
时间: 2024-03-27 09:37:32 浏览: 89
好的,我会为您编写一个基于TCP协议的网络通信程序,分别包括客户端和服务器端。
服务端代码如下:
```python
import socket
HOST = '127.0.0.1'
PORT = 8000
def handle_request(client_socket):
buf = client_socket.recv(1024)
user = buf.decode()
if user == 'liu':
client_socket.send(b'Hello, You are connected!')
else:
client_socket.send(b'Sorry, you are not the user!')
print('Received from client:', user)
client_socket.close()
if __name__ == '__main__':
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(1)
print('Server listening on port', PORT)
while True:
client_socket, client_addr = server_socket.accept()
print('Connected from', client_addr)
handle_request(client_socket)
```
客户端代码如下:
```python
import socket
HOST = '127.0.0.1'
PORT = 8000
if __name__ == '__main__':
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
user = input('Enter your username: ')
client_socket.send(user.encode())
response = client_socket.recv(1024)
print(response.decode())
client_socket.close()
```
使用方法:
1. 先运行服务端程序,命令行输入python server.py,服务端就会在本地8000端口监听客户端连接;
2. 再运行客户端程序,命令行输入python client.py,客户端会要求输入用户名,输入后按回车键发送给服务端;
3. 服务端接收到客户端发送的用户名后,判断是否为“liu”,根据判断结果发送不同的字符串给客户端;
4. 客户端接收到服务端发送的字符串后,打印输出,并关闭连接。
阅读全文