局域网两台电脑,两个IP。一台做服务器,一台做客户端。
1、服务器端代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import socket
import SocketServer
s = socket.socket()
host = '192.168.6.110'
#print('host', host)
port = 12345
s.bind((host, port))
print('server is start============')
s.listen(5)
while True:
c, addr = s.accept()
#print('wwwwwww:', addr)
c.send('from server!')
print c.recv(1024)
c.close()
2、客户端代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:client.py
import socket # 导入 socket 模块
import SocketServer
s = socket.socket() # 创建 socket 对象
host = '192.168.6.122' # 获取本地主机名
port = 12345 # 设置端口好
s.connect((host, port))
print s.recv(1024)
s.send('from client!')
s.close()
3、先运行服务器代码:

4、再运行客户端代码:
![]()
5、此时服务端显示:

该文章展示了如何使用Python的socket库在两台电脑之间建立服务器和客户端的通信。服务器端代码创建了一个socket,绑定到特定IP和端口,开始监听并响应客户端的连接请求。客户端则连接到服务器,接收并发送数据。
507

被折叠的 条评论
为什么被折叠?



