python-socket模块

socket server

#!/usr/bin/env python
# -*- coding:utf-8 -*- import socket ip_port = ('127.0.0.1',9999) sk = socket.socket()
sk.bind(ip_port)
sk.listen(5) while True:
print('server waiting...')
conn,addr = sk.accept() client_data = conn.recv(1024)
print("recv>",client_data.decode('utf-8')) resp = "我叫天南"
conn.sendall(resp.encode('utf-8'))
print("send>",resp) conn.close()

socket client

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
ip_port = ('127.0.0.1',9999) sk = socket.socket()
sk.connect(ip_port) sendstr = "你叫什么名字?"
sk.sendall(sendstr.encode('utf-8'))
print("send>",sendstr) server_reply = sk.recv(1024)
print("recv>",server_reply.decode('utf-8')) sk.close()

执行结果

client:
send> 你叫什么名字?
recv> 我叫天南 server:
server waiting...
recv> 你叫什么名字?
send> 我叫天南
server waiting...

一个简单的web服务器应用

#!/usr/bin/env python
#coding:utf-
import socket def handle_request(client):
buf = client.recv()
client.send("HTTP/1.1 200 OK\r\n\r\n".encode('utf-8'))
client.send("Hello, World".encode('utf-8')) def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost',))
sock.listen() while True:
connection, address = sock.accept()
handle_request(connection)
connection.close() if __name__ == '__main__':
main()

访问http://localhost:8080

python-socket模块

上一篇:Java多线程系列--“基础篇”02之 常用的实现多线程的两种方式


下一篇:MSSQLSERVER添加c# clr程序集的使用方法