Created
December 4, 2018 10:17
-
-
Save Koswu/470cf2cfe924321cc7c10419f722157f to your computer and use it in GitHub Desktop.
实现简单的类似nc的功能,连接echo服务端使用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
''' | |
An easy socket client | |
Author:KosWu | |
''' | |
import socket | |
import argparse | |
BUFFSIZE = 1024 | |
def main(): | |
#解析参数 | |
parser = argparse.ArgumentParser() | |
parser.add_argument('address', help='remote IP of the server') | |
parser.add_argument('-p', '--port', help='connect port of the server', type = int, default = 10007) | |
args = parser.parse_args() | |
port = args.port | |
if port not in range(1, 65535): | |
raise Exception("Port is out of range.") | |
addr = (args.address, args.port) | |
#连接对方,使用IPV4,TCP连接 | |
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
tcpSocket.connect(addr) | |
tcpSocket.settimeout(5) | |
try: | |
while True: | |
#从标准输入获取数据 | |
send_data = input() | |
if send_data == "": | |
continue | |
tcpSocket.send(bytes(send_data, encoding = 'utf-8')) | |
recv_data = tcpSocket.recv(BUFFSIZE) | |
recv_data = str(recv_data, encoding = 'utf-8') | |
print(recv_data) | |
except KeyboardInterrupt: | |
print ("Bye") | |
except Exception as err: | |
print(err) | |
tcpSocket.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment