基于TCP协议的聊天程序的设计代码
时间: 2024-01-15 08:02:42 浏览: 70
linux下基于TCP协议聊天程序
5星 · 资源好评率100%
这里给出一个简单的基于TCP协议的聊天程序的设计代码,其中客户端和服务器端均使用Python语言实现。
服务器端代码:
```python
import socket
host = '127.0.0.1'
port = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen()
print(f"Server is listening on {host}:{port}")
client_socket, client_address = server_socket.accept()
print(f"Connection established with {client_address[0]}:{client_address[1]}")
while True:
data = client_socket.recv(1024).decode()
if not data:
break
print(f"Received message: {data}")
message = input("Enter message to send: ")
client_socket.send(message.encode())
client_socket.close()
server_socket.close()
```
客户端代码:
```python
import socket
host = '127.0.0.1'
port = 9999
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
while True:
message = input("Enter message to send: ")
client_socket.send(message.encode())
data = client_socket.recv(1024).decode()
print(f"Received message: {data}")
client_socket.close()
```
以上代码仅为基础代码框架,可以根据实际需求进行修改和扩展。
阅读全文