socket_client.py
from socket import * clientSocket = socket(AF_INET, SOCK_STREAM) # create TCP socket print 'Socket Created' local_ip = gethostbyname(gethostname()) remotehost = 'www.google.com' remote_ip = gethostbyname(remotehost) print 'IP address of ' + remotehost + ' is ' + remote_ip print 'IP address of localhost is ' + local_ip port = 80 # port 80 for www.google.com clientSocket.connect((remotehost,port)) print 'Socket connected to ' + remotehost + ' on ip ' + remote_ip message = "GET/HTTP/1.1\r\n\r\n" clientSocket.send(message) # send message to www.google.com 80 reply = clientSocket.recv(1024) # receive message on 'reply' print 'reply received' clientSocket.close() # close connection print 'connection closed' |
message = "GET/HTTP/1.1\r\n\r\n" <- this might arouse curiosity to some people, refer below:
socket_server.py
from socket import * from socket import * # Problem a serverSocket = socket(AF_INET, SOCK_STREAM) #Create TCP socket print 'Socket Created' #Output HOST = '' #Symbolic name meaning all available interfaces PORT = 10000 #Arbitrary non-privileged port serverSocket.bind((HOST,PORT)) #Bind HOST to PORT print 'Socket bind complete' # Problem b
serverSocket.listen(10) #Listen to incoming connection print 'Socket now listening' # Problem c
conn, addr = serverSocket.accept() #Wait to accept a connection - blocking call print 'Connected with ' + addr[0] + ':' + str(addr[1]) #Display client information # Problem d
data = conn.recv(1024) #Receive input conn.sendall(data) #Echo what the client sends conn.close() #Close connection print 'Connection closed'
|
client side 에서 어떠한 메시지를 보내면...
다시 echo 를 보내고 connection 을 close 한다
Client 쪽에선 이와 같이 코딩하여 보냈다.
Server 쪽에 프로그래밍한대로 echo 만 반환한다.
Input 을 다시 받을 수 있도록 되어있지만, 실질적으로 서버쪽엔 connection 이 끊어져있기 때문에
무언가를 입력해서 enter 를 치면 아무것도 반환되지 않는다
from socket import * serverName = '~~~.~~~.123.171' serverPort = 10000 while 1: clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName,serverPort)) sentence = raw_input('Input:') clientSocket.send(sentence) modifiedSentence = clientSocket.recv(1024) print 'Server:', modifiedSentence clientSocket.close() |
WRITTEN BY