python实现socket通讯(TCP)

 Server:

 # server import socket address = ('127.0.0.1', 31500) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # s = socket.socket() s.bind(address) s.listen(5) ss, addr = s.accept() print 'got connected from',addr ss.send('byebye') ra = ss.recv(512) print ra ss.close() s.close()

 

Client:

# client import socket address = ('127.0.0.1', 31500) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(address) data = s.recv(512) print 'the data received is',data s.send('hihi') s.close()   

 

运行结果:

 

server

[[email protected] python]$ python server.py
got connected from ('127.0.0.1', 47872)
hihi

 

 

client

[[email protected] 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()

 

 

 

 

你可能感兴趣的:(网络,python,操作系统)