尝试在服务器到客户端之间发送命令

时间:2016-03-08 13:31:07

标签: tcp client-server python-3.1

我有两台机器,一台设置为客户端,另一台设置为服务器。客户端设置为从服务器接收命令然后响应。我知道......倒退。我尝试使用Putty,但一直接收连接被拒绝,然后发现客户端/服务器模型被颠倒了。以下代码似乎有效,但我无法验证数据是否已发送到客户端。感谢。

我的服务器程序如下:

# Sets up server on PC that it is run on.
# Attempting to send messages from Server to Client
# to run in windows open command prompt and from directory that the
#  file is located in and run it.  Or rund from IDLE.
# Python 3.1

import socketserver
import socket
from threading import *
import time

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        message = bytes('hello world from server'+'\n', 'utf-8')
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        print("Printed by Server - text From Client")
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())
        self.request.sendall(message)

# Added from website - http://stackoverflow.com/questions/21233340/sending-string-via-socket-python
class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            print('Client sent:', self.sock.recv(1024).decode())
            self.sock.send(b'Oi you sent something to me')


if __name__ == "__main__":
    HOST, PORT = "127.0.0.1", 5005 #HOST had to be IP of server
    # and PORT has to be available?

    # Create the server, binding to localhost on port XXXX
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

# Added from website - http://stackoverflow.com/questions/21233340/sending-string-via-socket-python
serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

终端服务器:

客户端:

# TCPClient - used to sen`enter code here`d data via TCP to Server
# Python 3.1

import socket
import sys

#HOST, PORT = "192.168.0.27", 85 #HOST port needs to be port of server (other machine)
# data = " ".join(sys.argv[1:])
#data = input("Enter a message you would like to send: ")
answer = "Y"


#Function serves data to Host and Port
def Serve(HOST, PORT, DATA):
    """Send and Receive Data To Server"""
    # Create a socket (SOCK_STREAM means a TCP socket)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        # Connect to server and send data
        sock.connect((HOST, PORT))
        sock.sendall(bytes(data + "\n", "utf-8"))

        # Receive data from the server and shut down
        received = str(sock.recv(1024), "utf-8")
    finally:
        sock.close()

    print("Sent:     {}".format(data), " HOST: ", HOST, " PORT: ", PORT)
    print("Received: {}".format(received))

while answer == "Y":
    data = input("Enter a message you would like to send: ")
    Serve("127.0.0.1", 5005, data)
    answer = input("Would you like to send another message? Y/N:")
    answer = answer.upper()

print("Good by")

终端客户:

随着IDLE: 服务器端

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
127.0.0.1 wrote:
b'hello'
Printed by Server - text From Client
127.0.0.1 wrote:
b'hello'
Printed by Server - text From Client
127.0.0.1 wrote:
b'hello'
Printed by Server - text From Client
127.0.0.1 wrote:
b'hello again'
Printed by Server - text From Client

客户端:

Enter a message you would like to send: hello
Sent:     hello  HOST:  127.0.0.1  PORT:  5005
Received: HELLO
Would you like to send another message? Y/N:y
Enter a message you would like to send: hello again
Sent:     hello again  HOST:  127.0.0.1  PORT:  5005
Received: HELLO AGAIN
Would you like to send another message? Y/N:n
Good by

0 个答案:

没有答案