简体   繁体   English

在套接字编程python中发送多个字符串

[英]Sending more than one string in socket programming python

I want to send data more than once. 我想多次发送数据。 I have the following code on server and client: 我在服务器和客户端上有以下代码:

On server : 在服务器上:

import socket
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)

serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))


serversocket.listen(5)
print('server started listening')
while 1:
    (clientsocket,address)=serversocket.accept()
    print("connection established from : ",address)
    data=clientsocket.recv(1024).decode()
    print(data)
    if (data=='hai'):
        GPIO.output(14,True)
        GPIO.output(15,False)
        print 'hello'
    else:
        GPIO.output(14,False)
        GPIO.output(15,False)
    clientsocket.send("data is sent".encode())

On client: 在客户端上:

import socket

s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
while True:

    in_data=raw_input(" Enter data to be sent > ")
    s.send(in_data.encode())
    s.send('hai'.encode())
    data = ''
    data = s.recv(1024).decode()
    print (data)
    s.close

I send the first string, get the response, but when I send the second string, it hangs. 我发送第一个字符串,得到响应,但是当我发送第二个字符串时,它挂起了。 How can I solve this? 我该如何解决?

Here is the code that worked 这是起作用的代码

On server : 在服务器上:

import socket
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)

serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))


serversocket.listen(5)
print('server started listening')
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
while 1:
    data=clientsocket.recv(1024).decode()
    print(data)
    if (data=='hai'):
        GPIO.output(14,True)
        GPIO.output(15,False)
        print 'hello'
    else:
        GPIO.output(14,False)
        GPIO.output(15,False)
    clientsocket.send("data is sent".encode())

On client: 在客户端上:

import socket

s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
    while True:

        in_data=raw_input(" Enter data to be sent > ")
        s.send(in_data.encode())
        data = ''
        data = s.recv(1024).decode()
        print (data)
finally:
    s.close()

This my client and it's working. 这是我的客户,它正在工作。

import socket

s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
    while True:
        in_data=raw_input(" Enter data to be sent > ")
        s.send(in_data.encode())
        s.send('hai'.encode())
        data = ''
        data = s.recv(1024).decode()
        print (data)
finally:
    s.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM