我理解为什么会得到:TypeError:getsockaddrarg:AF_INET地址必须是元组,而不是str

时间:2018-04-26 15:15:43

标签: python python-3.x sockets tuples

Okey,我一直盯着这两个代码,我无法理解为什么会收到这个错误:TypeError:getsockaddrarg:AF_INET地址必须是tuple,而不是str。

code1.py:     导入套接字     s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

import echoUDP

serveraddress = '0.0.0.0'
serverport = 5002

server2 = (server_address, server_port)
s.bind(server2)
print("Listening on " + server_address + ":" + str(server_port))
s.connect(('0.0.0.0',5005))

while True:
    client_address = ('0.0.0.0.')
    status = 'ok'
    print("Echoing back"+ str(status) + " to " + str(client_address))
    sen = s.sendto(status.encode(),clientaddress)

echoUDP.py:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server_address = '0.0.0.0'
server_port = 5005

server = (server_address, server_port)
sock.bind(server)
print("Listening on " + server_address + " Port: " + str(server_port))
sock.connect(('0.0.0.0', 5002))
while True:
    client_address = ('0.0.0.0')
    status = 'ok'
    print("Echoing back "+ str(status) + " to " + str(client_address))
    sen = sock.sendto(status.encode(),client_address)

有人可以告诉我没有得到什么吗? 我已经阅读了关于元组的其他问题,他们得到它是因为他们的sendto行,client_address不是元组。当我写client_address =('0.0.0.0')时,我以为我创建了这个元组?

1 个答案:

答案 0 :(得分:0)

class FlutterExample extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( body: new ListView( children: new List.generate(5, (i)=>new ListTileItem( title: "Item#$i", )), ), ); } } class ListTileItem extends StatefulWidget { String title; ListTileItem({this.title}); @override _ListTileItemState createState() => new _ListTileItemState(); } class _ListTileItemState extends State<ListTileItem> { int _itemCount = 0; @override Widget build(BuildContext context) { return new ListTile( title: new Text(widget.title), trailing: new Row( children: <Widget>[ _itemCount!=0? new IconButton(icon: new Icon(Icons.remove),onPressed: ()=>setState(()=>_itemCount--),):new Container(), new Text(_itemCount.toString()), new IconButton(icon: new Icon(Icons.add),onPressed: ()=>setState(()=>_itemCount++)) ], ), ); } } 的第二个参数应该是包含主机和端口的元组 - 例如sock.sendto()。所以在你的代码中,使用:

('0.0.0.0', 5005)

顺便说一句,sen = sock.sendto(status.encode(), (server_address, server_port)) 不是元组。 ('0.0.0.0')将是长度为1的元组。圆括号是Python中元组创建的可选项 - 它是一个逗号的存在,告诉Python你正在创建一个元组。这些例子应该说明。

('0.0.0.0',)