UDP客户端 - 服务器。客户端不向服务器发送字符串

时间:2017-04-19 11:13:32

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

如果偶数或奇数,我试图分割字符串:

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

"咖啡"将返回两个字符串 string1 =" Cof"和 string2 ="费用"

我有一个可行的算法。

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

我是python的新手。请帮忙。

Please find screenshot attached

服务器端:

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()

1 个答案:

答案 0 :(得分:2)

您可能需要重新访问splitWord()功能。

splitWord()内创建两个子字符串:s1和s2,但不要对它们执行任何操作(打印除外)。您的退货是空的,您也不会修改参数。

定义此功能的更好方法是:

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()