Python开发日志


自从我暑假学了一点Python基础以后,我就开始搞一些小事情。
近期刚刚学会了一点socket的东西。
再加上多线程。
我成功搞出了一点小事情。

Python开发日志1


  • 局域网聊天

我们需要import socket
利用里面的函数去搭建一个服务器。

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
ip = socket.gethostbyname(host)
port = 12345                # 设置端口
s.bind((ip, port))        # 绑定端口

print("初始化完成!您的IP地址为",ip,"。")

s.listen(5)                 # 等待客户端连接
while True:
   c, addr = s.accept()     # 建立客户端连接。
   print("连接地址:", addr)
   c.send(("喂?那端听得到么?").encode())  #encode是把字符串变成UTF-8格式,避免中文乱码
   c.close()                # 关闭连接

客户端

import socket               # 导入 socket 模块
import os

s = socket.socket()         # 创建 socket 对象
ip = input("输入IP:")
port = 12345                # 设置端口号

s.connect((host, port))
st = (s.recv(1024)).decode() #decode是解码 ,recv是接收,里面的参数是最大的字节
print(st)
s.close()  
os.system("pause")


  • 多线程模板

我们需要import threading

import time
import threading

class thread1(threading.Thread):
   def __init__(self):
       threading.Thread.__init__(self)
   def run(self):
       while 1:
           print('k')
           time.sleep(1)
class thread2(threading.Thread):
   def __init__(self):
       threading.Thread.__init__(self)
   def run(self):
       while 1:
           print('a')
           time.sleep(2)

thread_1=thread1()
thread_2=thread2()
thread_1.start()
thread_2.start()

好了。。。差不多这样了。。嗯。
应该够我写一个局域网rps了。
我将在下一个博客中写如何开发rps

相关文章: