gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
How to create a serversocket in python
- User
How to create a serversocket in python
- Assistant
To create a server socket in Python, you can use the
socketmodule. Here is a basic example:pythonimport socket # create a server socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # set the socket options server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind the socket to a specific address and port server_socket.bind(('localhost', 8080)) # listen for incoming connections server_socket.listen(1) # accept incoming connections while True: client_socket, client_address = server_socket.accept() print('Client connected from', client_address) # handle the incoming message message = client_socket.recv(1024) print(message) # send a response back to the client response = 'Hello, client!' client_socket.send(response.encode()) # close the connection client_socket.close()