python模块——socket

Posted 无荨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python模块——socket相关的知识,希望对你有一定的参考价值。

实例一、

server:
  #socket套接字(IP + 端口号)(qq,wechat 发送接收消息依靠socket模块),cs架构
import socket
server = socket.socket()
  #实例化出一个socket对象,默认tcp/ip协议
server.bind((\'127.0.0.1\',8888))
  #绑定客户端,VIP,元组形式,(\'\')相当于(\'0.0.0.0\')
  #声明出client端该访问那个地址和端口号
server.listen(5)
  #半连接池,listen(5)最大连接数
print(\'wait telephone..........\')
conn,addr = server.accept()
  #监听是否有客户端来连接
  #运行会产生两个返回值:连接信息,客户端信息
print(\'call telephone............\')
data = conn.recv(10240)
  #接收到的信息。10240:最大接受的字节,随便写\'
print(data.decode(\'utf-8\'))

client:
importsocket
client=socket.socket()
client.connect((\'127.0.0.1\',8888))
cmd=input(\'==>:\')
client.send(cmd.encode(\'utf-8\')) 

结果:

 

 

实例2、

利用subprocess模块和socket模块在其他主机执行cmd命令:
server:
import socket,subprocess
server = socket.socket()
server.bind((\'127.0.0.1\',8888))
server.listen(5)
print(\'wait telephone..........\')
conn,addr = server.accept()
print(\'call telephone............\')
while True:
    cmd = conn.recv(10240)
    process = subprocess.Popen(cmd.decode(\'utf-8\'),
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE
                               )
    stdout=process.stdout.read()
    stderr=process.stderr.read()
    result = stdout+stderr
    conn.send(result)

client:
import socket
client = socket.socket()
client.connect((\'127.0.0.1\',8888))
while True:
    cmd = input(\'==>:\').strip()
    if cmd:
        client.send(cmd.encode(\'utf-8\'))
    else:
        continue
    result = client.recv(10240)
    print(result.decode(\'gbk\'))

 结果: 

 

实例3、

简易聊天软件(首先利用socket建立两台机器的通信,再利用多线程让发送消息和接收消息同时运行。)

server:
import socket,threading
server = socket.socket()
server.bind((\'127.0.0.1\',8888))
server.listen(5)
print(\'wait telephone..........\')
conn,addr = server.accept()
print(\'call telephone............\')
def recv():
    while True:
        data = conn.recv(1024)
        print(data.decode(\'utf-8\'))
def send():
    while True:
        cmd = input(\'==>:\')
        conn.send(cmd.encode(\'utf-8\'))
t1 = threading.Thread(target=recv)
t2 = threading.Thread(target=send)
t1.start()
t2.start()


client:
import socket,threading
client = socket.socket()
client.connect((\'127.0.0.1\',8888))
def send():
    while True:
        cmd = input(\'==>:\').strip()
        client.send(cmd.encode(\'utf-8\'))
def recv():
    while True:
        data = client.recv(1024)
        print(data.decode(\'gbk\'))

t1 = threading.Thread(target=recv)
t2 = threading.Thread(target=send)
t1.start()
t2.start()

 结果:

 

 

实例4、

检查IP地址和端口号通不通:

import socket
hosts = [\'192.168.254.12:80\',\'192.168.254.12:3306\',\'2.2.2.2:80\',\'3.3.3.3:80\']
socket.setdefaulttimeout(1)

for host in hosts:
    ip = host.split(\':\')[0]
    port = host.split(\':\')[1]
    server = socket.socket()
    res = server.connect_ex((ip,int(port)))
    # 如果res为0代表ok,不为0代表连接失败
    if res == 0:
        print(\'%s is ok\' % ip)
    else:
        print(\'%s is 不ok\' % ip)


import socket
socket.setdefaulttimeout(1)            #超时时间
host_list = [\'192.168.4.145:5555\',\'192.168.4.146:555\',\'192.168.4.147:5555\',\'192.168.31.199:445\']
for info in host_list:
    server = socket.socket()
    ip = re.compile(\'(.*?):(.*)\').search(info).group(1)
    port = re.compile(\'(.*?):(.*)\').search(info).group(2)
    res = server.connect_ex((ip, int(port)))
    if res == 0:
        print(\'%s--%s端口正常\' % (ip, port))
    else:
        print(\'%s--%s端口异常\' % (ip, port))

以上是关于python模块——socket的主要内容,如果未能解决你的问题,请参考以下文章

python执行以下代码报:ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

Python 之 socket网络模块简单应用

python模块——socket (实现简单的C/S架构端通信操作CMD)

python之socket模块详解--小白博客

常用python日期日志获取内容循环的代码片段

Python socket 模块