有人可以用python网络pragram帮助我吗?

时间:2017-07-05 11:53:18

标签: python multithreading ssl python-multithreading

使用SSL / TLS和MultiThreading记下聊天程序代码库。

有三件事需要遵循。

1.当客户端连接客户端的ID和IP或网络接口信息时,网络信息。

2.当客户端发送消息时,您必须每次都遵循此表单([Client ID @ connect IP]消息)。

3.您必须使用客户端和服务器程序显示和解释流程图。

这是我对网络编程的期末考试。但这对我来说太难了。我无法写下代码。所以我不得不提交论文。我不知道该怎么做。有人可以解释如何编写程序代码吗?

我的代码是

server.py

import socket   
import thread

print '---python chatting program---'

host = ''    
port = 27332

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((host, port))

s.listen(1)

users = []

def service(conn):

    try:

        name = conn.recv(1024)

        str = '*' + name + ' is entered.*'

        while conn:

            print str

            for each in users:

                each.send(str)

            str = name + ' : ' + conn.recv(1024)

    except:

        users.remove(conn)

        str = '*' + name + ' is out.*'

        print str

        if users:

            for each in users: each.send(str)

# thread.start_new_thread(service, ())

while 1:

    conn, addr = s.accept()

    global users

    users.append(conn)

    thread.start_new_thread(service, (conn, ))

    pass

client.py

import socket  
import thread

def handle(socket):

    while 1:

        data = socket.recv(1024)

        if not data:

            continue

        print data

    print 'handler is end.'


host = '127.0.0.1'    
port = 27332  

print 'enter your name.'

name = raw_input()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, port))

s.send(name)

thread.start_new_thread(handle, (s, ))

while 1:

    msg = raw_input()

    if not msg:

        continue

    s.send(msg)

s.close()

print '---chatting program is end---'

1 个答案:

答案 0 :(得分:0)

官方Python文档提供了一个示例,说明如何使用Python的本地socket包来实现简单的echo服务器和客户端。该示例本身基本上不包含任何实际功能(因为此处的目标是演示socket的使用):服务器回显它从客户端接收的所有内容。但是,您可以使用此代码作为基础,根据需要添加功能。如果您使用Python 3,您将找到适用于Python 2 here的文档see here

现在为SSL / TLS部分。 Python有一个本机模块ssl,它是套接字对象的TLS / SSL包装器;引用官方Python文档:模块“提供对传输层安全性(通常称为”安全套接字层“)加密和网络套接字对等身份验证设施的访问”。如果您使用Python 3,则可以找到适用于Python 2 heressl模块see here的文档。

ssl模块提供了类ssl.SSLSocket,它派生自socket.socket类型,并提供类似套接字的包装器,它还使用SSL加密和解密通过套接字的数据。官方文档还包含可用于实现练习的示例代码(片段)({3}},了解如何使用Python 3中的ssl模块执行SSL / TLS。)

相关问题