1. 程式人生 > >httpd服務和apache

httpd服務和apache

服務器 示例 serve socket通信 code http python 通信 end

套接字相關的系統調用:
socket(): 創建一個套接字
bind():綁定IP和端口
listen():監聽
accept():接收請求
connect():請求連接建立
write():發送
read():接收
close():關閉連接

socket通信示例:

服務器端tcpserver.py

#/usr/bin/python
import socket
HOST=‘127.0.0.1‘
PORT=9527
BUFFER=4096
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((HOST,PORT))
sock.listen(3)
print(‘tcpServer listen at: %s:%s\n\r‘ %(HOST,PORT))
while True:
client_sock,client_addr=sock.accept()
print(‘%s:%s connect‘ %client_addr)
while True:
recv=client_sock.recv(BUFFER)
if not recv:
client_sock.close()
break
print(‘[Client %s:%s said]:%s‘ %(client_addr[0],client_addr[1],recv))
client_sock.send(‘tcpServer has received your message‘)
sock.close()

客戶端tcpclient

#/usr/bin/python
import socket
HOST=‘127.0.0.1‘
PORT=9527
BUFFER=4096
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((HOST,PORT))
sock.send(‘hello, tcpServer!‘)
recv=sock.recv(BUFFER)
print(‘[tcpServer said]: %s‘ % recv)
sock.close()

執行下面命令測試
python tcpserver
phthon tcpclient

httpd服務和apache