鱼C论坛

 找回密码
 立即注册
查看: 2053|回复: 0

[技术交流] GitHub上的socket小程序,很有意思。两个程序一个在cmd运行,一个在编译器运行

[复制链接]
发表于 2022-7-23 15:56:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
# Note :- Client and Server Must be connected to same Network
# import socket  modules
import socket

# create TCP/IP socket
s = socket.socket()
# take user input ip of server
server = input("Enter Server IP: ")
# bind the socket to the port 12345, and connect
s.connect((server, 12345))
# receive message from server connection successfully established
data = s.recv(1024).decode("utf-8")
print(server + ": " + data)

while True:
    # send message to server
    new_data = str(input("You: ")).encode("utf-8")
    s.sendall(new_data)
    # receive message from server
    data = s.recv(1024).decode("utf-8")
    print(server + ": " + data)

# close connection
s.close()

**********************************************************************

# Client and Server Must be connected to same network
# import socket module
import socket

# create TCP/IP socket
s = socket.socket()
# get the according IP address
ip = socket.gethostbyname(socket.gethostname())
# binding ip address and port
s.bind((ip, 12345))
# listen for incoming connections (server mode) with 3 connection at a time
s.listen(3)
# print your ip address
print("Server ip address:", ip)
while True:
    # waiting for a connection establishment
    print("waiting for a connection")
    connection, client_address = s.accept()
    try:
        # show connected client
        print("connected from", client_address)
        # sending acknowledgement to client that you are connected
        connection.send(str("Now You are connected").encode("utf-8"))

        # receiving the message
        while True:
            data = connection.recv(1024).decode("utf-8")
            if data:
                # message from client
                print(list(client_address)[0], end="")
                print(": %s" % data)
                # Enter your message to send to client
                new_data = str(input("You: ")).encode("utf-8")
                connection.send(new_data)
    finally:
        # Close connection
        connection.close()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-17 11:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表