【问题标题】:UDP client-server. Client not sending string to the serverUDP 客户端-服务器。客户端不向服务器发送字符串
【发布时间】:2017-04-19 11:13:32
【问题描述】:

我正在尝试拆分字符串,例如偶数或奇数:

"Tea" 将返回两个字符串 string1 = "Te" 和 string2 = "a" - 奇数

"Coffee" 将返回两个字符串 string1 = "Cof" 和 string2 = "fee"

我有一个有效的算法可以做到这一点。

然后客户端需要将此发送到服务器。我的问题是如何将其发送到服务器。服务器如何接受这两个字符串?

我是 python 的新手。请帮忙。

服务器端:

import socket


def Main():
    host = '127.0.0.1'
    port = 5000


    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    print("Server Started")
    while True:
        data, addr = s.recvfrom(1024)
        data = data.decode('utf-8')
        print("Message From:  " +str(addr))
        print("From connected user: " + data)
        data = data.upper()
        print("Sending: " + data)
        s.sendto(data.encode('utf-8'), addr)
    s.close()


if __name__ == '__main__':
    Main()

客户端:

      import socket

def Main():
    host = '127.0.0.1'
    port = 5001

    server = ('127.0.0.1', 5000)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    message = input('Please type a word ')
    while message != '':

        def splitWord(w):
            split = -((-len(w))//2)
            s1 = (w[:split])
            s2 = (w[split:])
            print(s1)
            print(s2)
            return


        a = splitWord(message)
        s.sendto(a.encode('utf-8'), server)

        data, addr = s.recvfrom(1024)
        data = data.decode('utf-8')
        print("Received from server: " + data)  
        message = input('-> ')
    s.close()

if __name__ == '__main__':
            Main()

【问题讨论】:

  • 你能发布输出吗?发球收到什么?客户收到回复了吗?

标签: python python-3.x network-programming udp


【解决方案1】:

您可能想重新访问您的 splitWord() 函数。

splitWord() 中创建两个子字符串:s1 和s2,但不要对它们做任何事情(除了打印)。你的 return 是空的,你也不修改参数。

定义此函数的更好方法是:

def splitWord(w):
  return w[:len(w)/2], w[len(w)/2:]

例子:

a = "Coffee"
f,s = splitWord(a)
print f, s

-> Cof fee 

也没有理由在 while 循环内定义 splitWord()

【讨论】:

  • @AlinaKhachatrian 你的 splitWord() 函数是错误的。我在上面建议了一个更短、更容易理解和正确的 splitWord() 函数。
  • message = input('请输入一个单词') while message != '': def splitWord(w): return w[:len(w)/2], w[len(w) /2:] s1, s2 = splitWord(message) print(s1) print(s2) 给我一个错误。 TypeError:切片索引必须是整数或无或具有索引方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-20
  • 2017-07-30
  • 2014-03-10
  • 1970-01-01
  • 2020-06-22
  • 2012-01-04
  • 1970-01-01
相关资源
最近更新 更多