Python:通过局域网连接? [英] Python: Connect via LAN?

查看:66
本文介绍了Python:通过局域网连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是这个问题的前言:我不知道我在做什么,所以请原谅我的愚蠢.

Just a preface to this question: I have no clue what I am doing, so please excuse any stupidity.

我正在制作一个基于套接字的聊天室,我想在本地网络上使用它(我爸爸的电脑和我的电脑通过同一个 wifi 连接).

I am making a socket based chatroom that I want to use on a local network (My dad's computer and mine connected through the same wifi).

这是服务器代码:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
sock.listen(1)
while True:
    # Find connections
    connection, client_address = sock.accept()
    try:
        data = connection.recv(999)
        print data

    except:
        connection.close()

这是客户:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 10000)
print >>sys.stderr, 'connecting to %s port %s' % server_address

while True:
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(server_address)
        message=raw_input('Message: ')
        if message=='quit':
            break
        sock.sendall(message)
    except:
        break
sock.close()

当我在一台计算机上运行客户端,而在另一台计算机上运行服务器时……没有建立连接.我相信这是因为 server_address = ('localhost', 10000) 但我不确定..有什么建议吗?

When I run the client on one computer, and the server on the other.. the connection isn't made. I believe it is because of server_address = ('localhost', 10000) but I am not sure.. any suggestions?

推荐答案

例如,如果您要成为服务器,则必须在服务器代码中使用您自己的 ip:

You have to use your local ip's for example if you are going to be the server you have to use your own ip in the server code:

查找ip:

ipconfig - Windows CMD
ifconfig - Linux Shell, Mac Terminal

知道你的ip后,你必须用你自己的ip替换localhost:

after you know your ip you have to replace localhost with your own ip:

服务器代码:

server_address = ('myip', 10000)

所以在你父亲的电脑上你必须连接到你的服务器:

so in your father's computer you have to connect to your server:

客户代码:

server_address = ('myip', 10000)

这篇关于Python:通过局域网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆