python socket如何实现一个服务器对多个客户端进行交互。

python socket如何实现一个服务器对多个客户端进行交互。,第1张

使用多线程,下面的代码,简单实现一个多线程的web服务器:

#coding=utf-8
import socket
import threading
from time import sleep
def response(sock, addr):
    print "收到请求"
    data = sockrecv(1024)
    print data
    socksend(html)
    sockclose()
html = '''>客户端简单代码:
Imports SystemNetSockets
Imports SystemIO
Private Output As NetworkStream
Private Writer As BinaryWriter
Private Reader As BinaryReader
Dim StrSend As String
Dim client As New TcpClient '
clientConnect(servIP, 2006)
Output = clientGetStream
Writer = New BinaryWriter(Output)
Reader = New BinaryReader(Output)
StrSend = "字符串"
SystemThreadingThreadSleep(100)
WriterWrite(StrSend)
Try
Message = ReaderReadString
If Message = "OK" Then
LBinfoText = "成功!" '测试
Else
LBinfoText = "失败!"
End If
SystemThreadingThreadSleep(100)
Catch ex As Exception
MessageBoxShow("Client Application Closing!")
Finally
WriterClose()
ReaderClose()
OutputClose()
clientClose()
End Try
服务器端
用线程
Imports SystemNetSockets
Imports SystemIO
Imports SystemThreading
Imports SystemWindowsForms
Private Connection As Socket
Private readThread As Thread
Private SocketStream As NetworkStream
Private Writer As BinaryWriter
Private Reader As BinaryReader
Public Sub New()
MyBaseNew()
'该调用是 Windows 窗体设计器所必需的。
InitializeComponent()
'在 InitializeComponent() 调用之后添加任何初始化
readThread = New Thread(AddressOf RunServer)
readThreadStart()
End Sub
Public Sub RunServer()
Dim Listener As TcpListener
Try
Listener = New TcpListener(NetIPAddressParse("192168116"), 2006)
ListenerStart()
While True
Connection = ListenerAcceptSocket 'accept an incoming connection
SocketStream = New NetworkStream(Connection) 'create networkstream object associated with socket
Writer = New BinaryWriter(SocketStream) 'create object for transferring data across stream
Reader = New BinaryReader(SocketStream) 'read string data sent from client
Try
Do
strIncept = ReaderReadString
strIncept = DataDisp(strIncept) '此处插入数据处理程序()
SendInfoToClient(strIncept) 'send to client
Loop While ConnectionConnected
Catch ex As Exception
MsgBox(exToString)
Finally
WriterClose()
ReaderClose()
SocketStreamClose()
End Try
End While
Catch ex As Exception
MsgBox(exToString)
End Try
End Sub
Public Sub SendInfoToClient(ByVal Info As String)
'Send to client
Try
If ConnectionConnected Then
WriterWrite(Info)
ConnectionClose()
End If
Catch ex As SocketException
MessageBoxShow(exToString)
End Try
End Sub
整个过程都有了


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zz/10228266.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-06
下一篇 2023-05-06

发表评论

登录后才能评论

评论列表(0条)

保存