I want to get a code about tcp with python
时间: 2024-05-10 16:20:43 浏览: 105
skhasp_IWant!IWant_python_
Here is an example code for creating a TCP client in Python:
```python
import socket
# create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get the server IP address and port number
server_address = ('localhost', 8888)
# connect to the server
client_socket.connect(server_address)
# send a message to the server
message = 'Hello, server!'
client_socket.sendall(message.encode())
# receive a response from the server
data = client_socket.recv(1024)
print('Received:', data.decode())
# close the connection
client_socket.close()
```
And here is an example code for creating a TCP server in Python:
```python
import socket
# create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a server address and port number
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# listen for incoming connections
server_socket.listen(1)
while True:
# accept a client connection
client_socket, client_address = server_socket.accept()
print('Connection from:', client_address)
# receive a message from the client
data = client_socket.recv(1024)
print('Received:', data.decode())
# send a response to the client
message = 'Hello, client!'
client_socket.sendall(message.encode())
# close the client connection
client_socket.close()
```
Note that in both examples, we are using the `socket` module to create a TCP socket object, and the `sendall()` and `recv()` methods to send and receive data over the connection.
阅读全文