如何使用Python中的ip地址将客户端连接到带有套接字的服务器?

时间:2016-04-23 23:18:43

标签: python sockets socketserver

这可能很简单,但我遇到了麻烦。 这是我用于服务器的代码。 我已经搜索了这个,但我只找到了不同类型的套接字。我正在使用它。

server = socket.socket()
server.bind(("localhost", 6969))
server.listen(1)
socket_client, datos_client = server.accept() 

print ("Wainting message...") 
data = socket_client.recv(1000) 
print ("Message:", data)

send1 = bytes("Bye","utf-8")
socket_client.send(send1)   

print ("Closing..." )

socket_client.close() 
server.close() 

这是客户端的代码:

import socket

def main():

    my_socket_client = socket.socket()
    my_socket_client.connect(("localhost", 6969))

    bufsize = 1000

    print("Send message")
    message=input()
    data2 = bytes(mensaje,"utf-8")
    #enviar los datos
    my_socket_client.send(data2)

    data_received= my_socket_client.recv(bufsize)

    print (data_received)

3 个答案:

答案 0 :(得分:1)

我不确定你的问题是什么,因为你没有问一个问题,所以我只会告诉你一个客户端+基本的命令服务器,我建立的就像你建立的一样,你说“我只发现了不同种类插座对我正在使用的插座。“所以我希望这就是你要找的东西

以下是一个简单命令服务器的示例: 如果您运行服务器代码然后运行客户端,您将能够键入客户端并发送到服务器。如果你键入TIME,你将从服务器获得一个响应,其中包含一个具有今天日期的字符串,其他命令以相同的方式工作。如果您输入EXIT,它将关闭连接,并将从服务器发送关闭到客户端的字符串

服务器:

import socket
import random
from datetime import date


server_socket = socket.socket()                           # new socket object
server_socket.bind(('0.0.0.0', 8820))                     # empty bind (will connect to a real ip later)

server_socket.listen(1)                                   # see if any client is trying to connect

(client_socket, client_address) = server_socket.accept()  # accept the connection
while True: # main server loop
    client_cmd = client_socket.recv(1024)                 # recive user input from client
    # check waht command was entered
    if client_cmd == "TIME":
        client_socket.send(str(date.today()))             # send the date
    elif client_cmd == "NAME":
        client_socket.send("best server ever")            # send this text
    elif client_cmd == "RAND":
        client_socket.send(str(random.randrange(1,11,1))) # send this randomly generated number
    elif client_cmd == "EXIT":
        client_socket.send("closing")
        client_socket.close()                             # close the connection with the client
        server_socket.close()                             # close the server
        break
    else :
        client_socket.send("there was an error in the commend sent")

client_socket.close()                                     # just in case try to close again
server_socket.close()                                     # just in case try to close again

客户端:

import socket

client_socket = socket.socket()                    # new socket object
client_socket.connect(('127.0.0.1', 8820))         # connect to the server on port 8820, the ip '127.0.0.1' is special because it will always refer to your own computer

while True:
    try:
        print "please enter a commend"
        print "TIME - request the current time"
        print "NAME - request the name of the server"
        print "RAND - request a random number"
        print "EXIT - request to disconnect the sockets"
        cmd = raw_input("please enter your name") # user input

        client_socket.send(cmd)                   # send the string to the server

        data = client_socket.recv(1024)           # recive server output
        print "the server sent: " + data          # print that data from the server
        print
        if data == "closing":
            break
    except:
        print "closing server"
        break

client_socket.close()                             # close the connection with the server

答案 1 :(得分:0)

你有一个错字。

在客户端编辑此行

data2 = bytes(mensaje,"utf-8")

data2 = bytes(message,"utf-8")

答案 2 :(得分:0)

我尝试了您的代码,并进行了一些更改:

服务器端:

import socket

server = socket.socket() 
server.bind(("localhost", 6969))     
server.listen(1)
socket_client, datos_client = server.accept() 
print ("Waiting message...") 
data = socket_client.recv(1000) 
print ("Message:", data )
# Same change made as with client side
send1 = bytes("Bye") #,"utf-8")
socket_client.send(send1) 
print ("Closing..." )    
socket_client.close() 
server.close()

客户方:

import socket

my_socket_client = socket.socket()
my_socket_client.connect(("localhost", 6969))
bufsize = 1000
print("Send message")
# I changed it to raw_input(); input() does not for string input with python 2.7
message=raw_input()
# Are you trying to encode the message? To make it simple, skip it
data2 = bytes(message) # ,"utf-8")
#enviar los datos
my_socket_client.send(data2)
data_received= my_socket_client.recv(bufsize)
print (data_received)

服务器端的示例输出:

Waiting message...
('Message:', 'message from client')
Closing...

客户端的示例输出:

Send message
message from client
Bye