Python socket 网络编程
socket可以实现网络上,两个程序的通信实现数据交换。
客户端
实现以下工作:
- 创建socket
- 建立连接
- 收发数据
# -*- coding:utf-8 -*-
import socket
import sys #for exit
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#socket()两个参数 Address Family: 可以选择AF_INET(用于Internet进程间通信),AF_UNIX(用于同一台机器进程间通信)
#Type :可以选择SOCKET_STREAM(流式套接字,主要用于TCP),SOCKET_DGRAM(数据报套接字,用于UDP)
except socket.error, msg: #错误处理
print 'Failed to create socket. Error code: ' + str(msg[0]) + ', Error message :' + msg[1]
sys.exit()
print 'Socket Created'
host = 'www.baidu.com'
port = 80
try:
remote_ip = socket.gethostbyname(host) #获取ip
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Ip address of' + host + ' is ' + remote_ip
#Connect to remote server
s.connect((remote_ip, port)) #进行连接
print 'Socket connected to ' + host + ' on ip ' + remote_ip
#Send some data to remote server
message= "GET / HTTP/1.1\r\n\r\n"
try:
s.sendall(message) #发送数据
except socket.error:
print 'Send failed'
sys.exit()
print 'Message send successfully'
#Now receive data
reply = s.recv(4096) #接受长度为4096字节的数据
print reply
s.close()
执行结果
服务端
实现以下工作:
- 创建socket
- 绑定socket到特定的地址及端口
- 监听连接
- 建立连接
- 接发数据
要实现多个用户连接并且发送多条数据,需要用到线程。
code:
# -*- coding:utf-8 -*-
import socket
import sys
from thread import *
HOST = ''
PORT = 8888
s =socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT)) #绑定socket 到地址和端口上
except socket.error, msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket blind complete'
s.listen(10) #进行监听
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type somthing and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end
while True:
#Receiving from client
data = conn.recv(1024)
if not data:
break
print addr[0] + ':' + str(addr[1]) + ' say:' + data
conn.sendall(data)
#now keep talking whith the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
#display client informaiton
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function
start_new_thread(clientthread, (conn,))
s.close()
执行结果
可以由多个终端连接,并且可以发送多条信息。