Python的简单socket操作

发布时间:2019-09-19 08:06:40编辑:auto阅读(1859)

    import socket

    host = ''
    port = 12345

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((host, port))
    s.listen(1)

    print "Server is running on port %d; press Ctrl-C to terminate." % port

    while 1:
        clientsock, clientaddr = s.accept()
        clientfile = clientsock.makefile('rw', 0)
        clientfile.write("Welcome, " + str(clientaddr) + "\n")
        clientfile.write("Please enter a string: ")
        line = clientfile.readline().strip()
        clientfile.write("Hello %s. ^_^ How are you Today! \n" % line)
        clientfile.close()
        clientsock.close()

    /// telnet localhost 12345

    Welcome, ('127.0.0.1', 3190)
                                Please enter a string: woody
    Hello woody. ^_^ How are you Today!


    失去了跟主机的连接。

    C:\Documents and Settings\Administrator>

关键字