Python套接字连接

时间:2015-11-25 18:30:03

标签: python sockets

我想连接不在我的局域网中的计算机。我想连接真正的IP。

我的服务器代码

import json
import os
import select
import socket
import sys
import urllib
import urllib.request
from optparse import OptionParser

ip = json.loads(urllib.request.urlopen('http://httpbin.org/ip').read().decode("utf-8"))['origin']
print(ip)


def isAlive(ip):
    ret = os.system("ping -o -c 3 -W 3000 " + ip)
    if ret != 0:
        return True
    return False


HOST = socket.gethostname()

SOCKET_LIST = []
RECV_BUFFER = 1024
PORT = 1993

def chat_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((HOST, PORT))
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.listen(10)

    # add server socket object to the list of readable connections
    SOCKET_LIST.append(server_socket)

    print("Chat server started on port " + str(PORT), "on Host " + str(HOST))
    print(SOCKET_LIST)
    while True:
        ready_to_read, ready_to_write, in_error = select.select(SOCKET_LIST, [], [], 0)

        for sock in ready_to_read:
            if sock == server_socket:
                sockfd, addr = server_socket.accept()
                SOCKET_LIST.append(sockfd)
                print("Client (%s, %s) connected" % addr)
                broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
            else:
                try:
                    data = sock.recv(RECV_BUFFER)
                    recvString = data.decode("utf-8")
                    print(recvString)
                    if data:
                        broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
                    else:
                        if sock in SOCKET_LIST:
                            SOCKET_LIST.remove(sock)
                        broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
                except:
                    broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
                    continue

    server_socket.close()


def broadcast(server_socket, sock, message):
    for socket in SOCKET_LIST:
        if socket != server_socket and socket != sock:
            try:
                socket.send(message)
            except:
                socket.close()
                if socket in SOCKET_LIST:
                    SOCKET_LIST.remove(socket)





if __name__ == "__main__":
    sys.exit(chat_server())

连接代码

import socket

print(socket.getaddrinfo("localhost", 80, 0, 0, socket.SOL_TCP))
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket successfully created")
    print(socket.gethostbyname(socket.gethostname()))
except socket.error as err:
    print("socket creation failed with error %s" % (err))

port = 1993
host_ip = '193.140.109.2'
s.connect((host_ip, port))

while True:
    getGet = input("Send Data: ")
    s.sendall(bytearray(getGet, 'utf8'))

    if getGet == '-':
        s.close()

我写了这段代码,但我无法连接我的电脑。我有一些问题。 1-仅适用于LAN连接的插座吗? 2-如何连接不同的计算机?

1 个答案:

答案 0 :(得分:0)

s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
port = 1993
host_ip = 'fe80::d862:a887:2f4c:53d0%12'

解决了我的问题。