网络编程初识
tcp聊天室
snd_tcp.py
# -*- coding: utf-8 -*-
# @Time : 2019/11/28 11:03
# @Author : Han lei
# @Email : hanlei5012@163.com
# @File : snd_tcp.py
# @Software: PyCharm
import socket
import threading
def snd_snd():
while 1:
snd_data = input()
s.send(snd_data.encode())
def snd_rec():
while 1:
rec_data = s.recv(1024)
print(f'服务器:{rec_data.decode()}')
if __name__ == "__main__":
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.25.58.132',8000))
# t1 = threading.Thread(target=snd_snd())
t1 = threading.Thread(target=snd_snd)
t2 = threading.Thread(target=snd_rec)
t1.start()
t2.start()
t1.join()
t2.join()
serv_tcp.py
# -*- coding: utf-8 -*-
# @Time : 2019/11/28 11:02
# @Author : Han lei
# @Email : hanlei5012@163.com
# @File : serv_tcp.py
# @Software: PyCharm
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1',8000))
s.listen(5)
sock,sock_addr = s.accept()
def serv_rec():
while True:
data = sock.recv(1024)
print(f'客户端:{data.decode()}')
def serv_snd():
while True:
snd_data = input()
sock.send(snd_data.encode())
t1 = threading.Thread(target=serv_rec)
t2 = threading.Thread(target=serv_snd)
t1.start()
t2.start()
t1.join()
t2.join()
udp聊天室
snd_udp.py
# -*- coding: utf-8 -*-
# @Time : 2019/11/28 9:41
# @Author : Han lei
# @Email : hanlei5012@163.com
# @File : serv_udp.py
# @Software: PyCharm
import socket
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('127.0.0.1',1234))
while True:
snd_data = input()
s.sendto(snd_data.encode(), ('127.0.0.1', 8000))
rec_data = s.recv(1024)
print(rec_data.decode())
if __name__ == '__main__':
main()
serv_udp.py
# -*- coding: utf-8 -*-
# @Time : 2019/11/28 9:41
# @Author : Han lei
# @Email : hanlei5012@163.com
# @File : serv_udp.py
# @Software: PyCharm
import socket
# SOCK_DGRAM udp模式
def main():
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('127.0.0.1', 8000))
while True:
rec_data = s.recv(1024)
print(rec_data.decode())
snd_data = input()
s.sendto(snd_data.encode(),('127.0.0.1',1234))
if __name__ == '__main__':
main()
另:
- pyqt5 做界面的,可以用这个和网络知识自己做一个飞秋
- TCP/IP详解卷一,可以学各种协议
- 鸟哥的linux私房菜,可以学linux
- Bind()作用:(接收方一定要有bind,要不发送端不知道往哪发)
- 127.0.0.1 是本机的地址
- 临界资源:多个线程或进程操作资源