Python套接字回复端口

时间:2016-08-05 20:10:32

标签: python sockets

如何选择客户回复的端口?服务器正在侦听5800,我希望客户端使用端口5801进行重放。如果不是,如果该端口未打开,将会发生什么情况。这适用于FRC,它只有有限数量的端口打开,目前它是随机的。

客户端:

#!/usr/bin/env python

import socket
import sys


TCP_IP = '127.0.0.1'
TCP_PORT = 5800
BUFFER_SIZE = 1024
nodata = 0

while True:
    MESSAGE = raw_input("Please enter a color: ")
    if MESSAGE == "":
        MESSAGE = "0,255,0"

    if "," in MESSAGE:
        print "you entered", MESSAGE
        break
    else:
        print "Not a Color."

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))
    s.send(MESSAGE)
    data = s.recv(BUFFER_SIZE)
    s.close()
except Exception:
    print "No Connection or Wrong Ip Address"
    nodata = 1

if nodata == 1:
    print "No Data Sent. Server Should Default Green."
else:
    print "sent data:", data

服务器:

#!/usr/bin/env python

import socket
#from neopixel import *

# Create NeoPixel object with appropriate configuration.
#strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL,
#                          LED_STRIP)
# Intialize the library (must be called once before other functions).
#strip.begin()

# Server Variables
TCP_IP = '127.0.0.1'
TCP_PORT = 5800
BUFFER_SIZE = 20  # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

# Neopixel Variables
LED_COUNT = 12  # Number of LED pixels.
LED_PIN = 18  # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 5  # DMA channel to use for generating signal (try 5)
LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest

#Color Variables
color = ""
Red = "0"
Green = "255"
Blue = "0"

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    color = data
    print "Color Received:", data
    conn.send(data)  # echo
conn.close()

print "Color: ", color

#Color Choosing
Red, Green, Blue = color.split(",")
print "Red: ", Red
print "Green: ", Green
print "Blue: ", Blue
#for i in range(0,LED_COUNT):
    #strip.setPixelColor(i, color(Red, Green, Blue))
#strip.show()

0 个答案:

没有答案