【问题标题】:Socket - host invalid syntax? python套接字 - 主机无效语法? Python
【发布时间】:2014-02-12 10:58:56
【问题描述】:

是的,所以我正在一台机器上的两个程序之间制作一个简单的通信器,尽管我打算将程序放在两台机器上并让它们在本地 LAN 上通信。我在 client.py 上的主机上收到无效语法

-Server.py

import socket

s = socket.socket()         
host = socket.gethostname() 
port = 12345                
s.bind((host, port))        

s.listen(5)                 
while True:
   c, addr = s.accept()     
   print ('Got connection from', addr)
   c.send("Thank you for connecting".encode())
   c.close()

client.py

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = 192.168.1.161  
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print (s.recv(1024))
s.close                     # Close the socket when done

我正在使用 Python 3.x

【问题讨论】:

  • 除了不引用host 字符串之外,您实际上并没有调用 s.close 方法。 s.close() 将是一个电话。
  • 谢谢,我困惑的原因是你为什么不用把端口号放在引号里?
  • 因为它是一个int字面量;它是一个自然数。另一方面,IP 地址在 Python 中不是文字值。

标签: python sockets networking python-3.x syntax


【解决方案1】:

你应该引用主机字符串:

host = "192.168.1.161"

【讨论】:

    猜你喜欢
    • 2020-12-18
    • 2012-07-17
    • 1970-01-01
    • 2020-08-13
    • 2020-05-31
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多