Python - Socket 通信

服务端:

# This module provides access to the BSD socket interface.
# It is available on all modern Unix systems, Windows, MacOS,
# and probably additional platforms.
import socket


def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        host = "8.8.8.8"
        port = 80
        address = (host, port)
        s.connect(address)
        
        sockname = s.getsockname()

        ip = sockname[0]
        port = sockname[1]
    finally:
        s.close()

    return ip


# socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
# Create a new socket using the given address family, socket type and protocol number.
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("Socket Server: ", socket_server)

host = get_host_ip()
port = 9000
address = (host, port)
# socket.bind(address)
# Bind the socket to address. The socket must not already be bound.
socket_server.bind(address)

# socket.listen([backlog])
# Enable a server to accept connections.
# If backlog is specified, it must be at least 0 (if it is lower, it is set to 0);
# it specifies the number of unaccepted connections
# that the system will allow before refusing new connections.
# If not specified, a default reasonable value is chosen.
socket_server.listen()

# Accept a connection. The socket must be bound to an address and listening for connections.
# The return value is a pair (conn, address)
# where conn is a new socket object usable to send and receive data on the connection,
# and address is the address bound to the socket on the other end of the connection.
conn, address = socket_server.accept()

# socket.recv(bufsize[, flags])
# Receive data from the socket.
# The return value is a bytes object representing the data received.
# The maximum amount of data to be received at once is specified by bufsize.
# See the Unix manual page recv(2) for the meaning of the optional argument flags;
# it defaults to zero.
received_data = conn.recv(1024)

print("Received data from the socket: ", received_data.decode("utf-8"))

# Mark the socket closed.
# The underlying system resource (e.g. a file descriptor) is also closed
# when all file objects from makefile() are closed.
# Once that happens, all future operations on the socket object will fail.
# The remote end will receive no more data (after queued data is flushed).
socket_server.close()

客户端:

# This module provides access to the BSD socket interface.
# It is available on all modern Unix systems, Windows, MacOS,
# and probably additional platforms.
import socket


def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        host = "8.8.8.8"
        port = 80
        address = (host, port)
        s.connect(address)
        
        sockname = s.getsockname()

        ip = sockname[0]
        port = sockname[1]
    finally:
        s.close()

    return ip


# socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
# Create a new socket using the given address family, socket type and protocol number.
socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("Socket Client: ", socket_client)

host = get_host_ip()
port = 9000
address = (host, port)
# socket.connect(address)
# Connect to a remote socket at address.
socket_client.connect(address)

print("Connected to a remote socket at address: ", address)

data = "The data I want to send. 我想要发送的数据。"

# Send data to the socket.
# The socket must be connected to a remote socket.
# The optional flags argument has the same meaning as for recv().
# Returns the number of bytes sent.
# Applications are responsible for checking that all data has been sent;
# if only some of the data was transmitted,
# the application needs to attempt delivery of the remaining data.
socket_client.send(data.encode("utf-8"))

# Mark the socket closed.
# The underlying system resource (e.g. a file descriptor) is also closed
# when all file objects from makefile() are closed.
# Once that happens, all future operations on the socket object will fail.
# The remote end will receive no more data (after queued data is flushed).
socket_client.close()

print("Send data completed...")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值