通过套接字发送字符串(python) [英] Sending string via socket (python)
问题描述
我有两个脚本,Server.py和Client.py. 我有两个目标:
I have two scripts, Server.py and Client.py. I have two objectives in mind:
- 能够一次又一次地从客户端向服务器发送数据.
- 能够将数据从服务器发送到客户端.
这是我的Server.py:
here is my Server.py :
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))
serversocket.listen(5)
print ('server started and listening')
while 1:
(clientsocket, address) = serversocket.accept()
print ("connection found!")
data = clientsocket.recv(1024).decode()
print (data)
r='REceieve'
clientsocket.send(r.encode())
这是我的客户:
#! /usr/bin/python3
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host ="192.168.1.3"
port =8000
s.connect((host,port))
def ts(str):
s.send('e'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
while 2:
r = input('enter')
ts(s)
s.close ()
该函数首次运行("e"进入服务器,我返回返回消息),但是如何使它一遍又一遍地发生(类似于聊天应用程序)? 该问题在第一次之后开始.消息不会在第一次之后发送. 我究竟做错了什么? 我是python的新手,所以请详细说明一下,如果可以的话,请提供整个内容的源代码.
The function works for the first time ('e' goes to the server and I get return message back), but how do I make it happen over and over again (something like a chat application) ? The problem starts after the first time. The messages don't go after the first time. what am I doing wrong? I am new with python, so please be a little elaborate, and if you can, please give the source code of the whole thing.
推荐答案
import socket
from threading import *
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.start()
def run(self):
while 1:
print('Client sent:', self.sock.recv(1024).decode())
self.sock.send(b'Oi you sent something to me')
serversocket.listen(5)
print ('server started and listening')
while 1:
clientsocket, address = serversocket.accept()
client(clientsocket, address)
这是一个非常简单的设计,可以解决您的问题.
首先,您需要在进入while 1
循环之前接受客户端(服务器端),因为在每个循环中您都接受一个新的客户端,或者按照我的描述,您将客户端扔到一个单独的线程中,从现在开始自己处理.
This is a very VERY simple design for how you could solve it.
First of all, you need to either accept the client (server side) before going into your while 1
loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.
这篇关于通过套接字发送字符串(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!