通过套接字发送字符串(python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21233340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:22:07  来源:igfitidea点击:

Sending string via socket (python)

pythonsocketsnetworking

提问by harveyslash

I have two scripts, Server.py and Client.py. I have two objectives in mind:

我有两个脚本,Server.py 和 Client.py。我有两个目标:

  1. To be able to send data again and again to server from client.
  2. To be able to send data from Server to client.
  1. 能够一次又一次地从客户端向服务器发送数据。
  2. 能够将数据从服务器发送到客户端。

here is my Server.py :

这是我的 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())

and here is my client :

这是我的客户:

#! /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 ()

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.

该函数第一次工作('e' 进入服务器,我得到返回消息),但是我如何让它一遍又一遍地发生(类似于聊天应用程序)?问题在第一次之后开始。消息不会在第一次之后发送。我究竟做错了什么?我是python新手,所以请详细一点,如果可以,请给出整个事情的源代码。

采纳答案by Torxed

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)

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 1loop 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.

这是一个关于如何解决它的非常非常简单的设计。首先,您需要在进入while 1循环之前接受客户端(服务器端),因为在每个循环中您都接受一个新客户端,或者您按照我的描述进行操作,将客户端扔到一个单独的线程中从此拥有。

回答by gravetii

This piece of code is incorrect.

这段代码不正确。

while 1:
    (clientsocket, address) = serversocket.accept()
    print ("connection found!")
    data = clientsocket.recv(1024).decode()
    print (data)
    r='REceieve'
    clientsocket.send(r.encode())

The call on accept()on the serversocketblocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.

在电话会议上accept()serversocket阻塞,直到有一个客户端连接。当您第一次从客户端连接到服务器时,它接受连接并接收数据。然而,当它再次进入循环时,它正在等待另一个连接,因此由于没有其他客户端尝试连接而阻塞。

That's the reason the recvworks correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.

这就是recv作品仅在第一次正确的原因。您应该做的是找出如何处理与已被接受的客户端的通信 - 也许通过创建一个新线程来处理与该客户端的通信并继续接受循环中的新客户端,以相同的方式处理它们。

Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.

提示:如果您想创建自己的聊天应用程序,您应该查看像 Twisted 这样的网络引擎。它也将帮助您更好地理解整个概念。

回答by Nischaya Sharma

client.py

客户端.py

import socket

s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
    str = raw_input("S: ")
    s.send(str.encode());
    if(str == "Bye" or str == "bye"):
        break
    print "N:",s.recv(1024).decode()
s.close()

server.py

服务器.py

import socket

s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
    rcvdData = c.recv(1024).decode()
    print "S:",rcvdData
    sendData = raw_input("N: ")
    c.send(sendData.encode())
    if(sendData == "Bye" or sendData == "bye"):
        break
c.close()

This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.

这应该是您想要的聊天应用程序的小型原型的代码。在单独的终端中运行它们,然后只检查端口。