Server:
# server</p><p>import socket</p><p>address = ('127.0.0.1', 31500)<br />s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # s = socket.socket()<br />s.bind(address)<br />s.listen(5)</p><p>ss, addr = s.accept()<br />print 'got connected from',addr</p><p>ss.send('byebye')<br />ra = ss.recv(512)<br />print ra</p><p>ss.close()<br />s.close()<br />
Client:
# client</p><p>import socket</p><p>address = ('127.0.0.1', 31500)<br />s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br />s.connect(address)</p><p>data = s.recv(512)<br />print 'the data received is',data</p><p>s.send('hihi')</p><p>s.close()<br />
運行結果:
server
[work@db-testing-com06-vm3.db01.baidu.com python]$ python server.py
got connected from ('127.0.0.1', 47872)
hihi
client
[work@db-testing-com06-vm3.db01.baidu.com python]$ python client.py
the data received is byebye
==============================================================================
參考資料:http://www.cppblog.com/lai3d/archive/2008/02/19/42919.html
一個簡單的伺服器和用戶端通訊的例子
伺服器:
import socket
s=socket.socket()
s.bind(('xxx.xxx.xxx.xxx',xxxx)) #ip地址和連接埠號碼
s.listen(5)
cs,address = s.accept()
print 'got connected from',address
cs.send('byebye')
ra=cs.recv(512)
print ra
cs.close()
用戶端:
import socket
s=socket.socket()
s.connect(('xxx.xxx.xxx.xxx',xxxx)) #與伺服器程式ip地址和連接埠號碼相同
data=s.recv(512)
s.send('hihi')
s.close()
print 'the data received is',data
運行:
在本機測試(windows環境下,可以將ip地址改為本機ip,連接埠號碼在1024以上,windows將1024以下的為保留),運行--CMD--進入命令列模式
先python 伺服器程式,後python 用戶端程式即可。
或者啟動伺服器程式後,用telnet ip地址 連接埠號碼,也可以得到同樣結果。
讓server持續接受串連
server.py
import socket
s=socket.socket()
s.bind(('192.168.43.137',2000))
s.listen(5)
while 1:
cs,address = s.accept()
print 'got connected from',address
cs.send('hello I am server,welcome')
ra=cs.recv(512)
print ra
cs.close()
測試兩個一個程式中兩個socket並存是否可行
client.py
import socket
s=socket.socket()
s.connect(('192.168.43.137',2000))
data=s.recv(512)
print 'the data received is/n ',data
s.send('hihi I am client')
sock2 = socket.socket()
sock2.connect(('192.168.43.137',2000))
data2=sock2.recv(512)
print 'the data received from server is/n ',data2
sock2.send('client send use sock2')
sock2.close()
s.close()