All the "server" example in scala use actors, reactors etc...
Can someone show me how to write a dead simple echo server and client, just like the following python example of Server and Client:
# A simple echo server
import socket
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
if data:
client.send(data)
client.close()
# A simple echo client
import socket
host = 'localhost'
port = 50000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send('Hello, world')
data = s.recv(size)
s.close()
print 'Received:', data
You can do following within standard library:
// Simple server
import java.net._
import java.io._
import scala.io._
val server = new ServerSocket(9999)
while (true) {
val s = server.accept()
val in = new BufferedSource(s.getInputStream()).getLines()
val out = new PrintStream(s.getOutputStream())
out.println(in.next())
out.flush()
s.close()
}
// Simple client
import java.net._
import java.io._
import scala.io._
val s = new Socket(InetAddress.getByName("localhost"), 9999)
lazy val in = new BufferedSource(s.getInputStream()).getLines()
val out = new PrintStream(s.getOutputStream())
out.println("Hello, world")
out.flush()
println("Received: " + in.next())
s.close()
If you don't mind using extra libraries, you might like Finagle.
I just wrote a blog post about using Akka IO and Iteratees to create a simple command based socket server.
Maybe it could be of interest.
http://leon.radley.se/2012/08/akka-command-based-socket-server/
You would have to use Java Sockets. I found a nice example of a Scala Socket Server/Client at: http://www.scala-lang.org/node/55
You can use netty java library. Here is an example usage in Scala:
https://github.com/mcroydon/scala-echo-server
Generally you need to use Java Socket API. In this example Java Socket API are used, but the whole server is wrapped in Actor in order to process clients in separate thread and not to block acceptor thread (the same thing you will normally do in Java, but you will use threads directly).
Josh Suereth recently posted an example of an NIO echo server using scalaz Iteratees. Requires the scalaz library
Related
Write down the chatting program code base with SSL/TLS and MultiThreading.
there's a 3 things to follow.
1.when client connected client's ID and IP or Network interface information, network information.
2.when client send message you have to follow this form([Client ID#connect IP] Message ) everytime.
3.you have to show and explain flowchart with client and server program.
it's my final exam of network programing. but it's too hard for me. i couldn't write down the code. so i have to submit the paper with nothing. i don't know how to do. someone can explain how to code the program?
my code is
server.py
import socket
import thread
print '---python chatting program---'
host = ''
port = 27332
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
users = []
def service(conn):
try:
name = conn.recv(1024)
str = '*' + name + ' is entered.*'
while conn:
print str
for each in users:
each.send(str)
str = name + ' : ' + conn.recv(1024)
except:
users.remove(conn)
str = '*' + name + ' is out.*'
print str
if users:
for each in users: each.send(str)
# thread.start_new_thread(service, ())
while 1:
conn, addr = s.accept()
global users
users.append(conn)
thread.start_new_thread(service, (conn, ))
pass
client.py
import socket
import thread
def handle(socket):
while 1:
data = socket.recv(1024)
if not data:
continue
print data
print 'handler is end.'
host = '127.0.0.1'
port = 27332
print 'enter your name.'
name = raw_input()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(name)
thread.start_new_thread(handle, (s, ))
while 1:
msg = raw_input()
if not msg:
continue
s.send(msg)
s.close()
print '---chatting program is end---'
The official Python documentation provides an example of how to use Python's native socket package to implement a simple echo server and client. The example itself contains essentially no real functionality (since the goal here is to demo the use of socket): the server echoes back everything it receives from the client. However, you can use this code as a basis, adding the functionality as required. If you use Python 3, you'll find the documentation here, for Python 2 see here.
Now for the SSL/TLS part. Python has a native module ssl which is a TLS/SSL wrapper for socket objects; to cite the official Python documentation: the module "provides access to Transport Layer Security (often known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets". If you use Python 3, you can find the documentation for the ssl module here, for Python 2 see here.
The ssl module provides the class ssl.SSLSocket, which is derived from the socket.socket type, and provides a socket-like wrapper that also encrypts and decrypts the data going over the socket with SSL. The official documentation also contains example code (snippets) you can use to implement your exercise (see e.g. here for how to do SSL/TLS using ssl module in Python 3).
I am currently developing a system where I need to send notification to Raspberry to run a Python file. It is much like a observer pattern design where my server is publisher and Raspberry is the observer. Worth to note that, I actually need to interact with one Raspberry at the time (even I have dozens of them). Specifically, on a specific event, I need to warn a single Raspberry that it has to take an action.
I searched for it literally for all the night but I could not find anything coming handy. Nothing really give me a clue how to implement this.
The most close answer I could find is this technology firm's product called PubNub which can actually work. However, as I need is a one-to-one interaction, this might be unnecessary because it is designed to publish a data to multiple clients.
Long story short, I need to trigger Raspberry to take some action in accordance to the some data coming from the server, whenever it receives the data.
Server is running on Amazon and implemented with Python 2.7.
Please do not hesitate to ask me for further detail, if I am missing any.
Thanks for all the supports,
EDIT
Just a recent update with an improvement to my answer. As far as I understand, sockets are able to manage this process. Such as from client (Raspberry in my case) listening for the server and server sending some data. Taken from this site, I managed to make a sample run on my computer, from my local. I used Port 5000 as their 'meeting point'.
Below is the code:
client.py
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5000
BUFFER_SIZE = 1024
MESSAGE = b"Hello, World!"
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()
print("received data:", data)
server.py
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5000
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)
conn, addr = s.accept()
print('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print("received data:", data)
conn.send(data) # echo
conn.close()
However, I still have some questions.
Firstly, I want to learn whether the same thing work when I deploy the project and how. If that will work - lets say I have an url for the server like 'www.thisisanexampleurl.com' - simply assignign a port for it, will work?
Secondly, assuming first question is done, what is the way of making it continous so that it does not stop after receiving and sending data once. Because currently, when it makes the data transfer, it stops working.
Thanks again for the all support and again please do not hesitate to ask me for the further details i am missing any.
You should be able to do something this simple:
Run something like this on your pi:
import socket
s = socket.socket()
host = ""
port = 12345
s.bind((host, port))
s.listen(5)
while True:
try:
clientsock, addr = s.accept()
except OSError:
continue
message = clientsock.recv(20)
#the code you want to run
print("doing %s" % message)
clientsock.close()
And this on your server every time you want the pi to take action:
import socket
s = socket.socket()
host = "0.0.0.0"
port = 12345
s.connect((host, port))
s.send("foo")
s.close()
Have a look at Pyro4. It lets you avoid having to write network code at all and just write code that calls remote Python objects as if they were running on the same machine. In your case, the server could call a normal Python method on your Raspberry Pi to do something. It has many features but you can start with something extremely simple.
raspberry pi code:
import Pyro4
#Pyro4.expose
class Raspberry:
def something(self, arg):
print("called with:", arg)
return "hi from pi"
Pyro4.Daemon.serveSimple({Raspberry: "raspberry"})
server code to make the pi do something:
import Pyro4
rasp = Pyro4.Proxy("PYRONAME:raspberry")
print(rasp.something(42))
I am trying to modify a tcp/ip server-client communication. Only the server can communicate with the client. I am trying to find an easy a way to send a message back to the server. Not a chat !! Just a server which will send data to a client and receive data from the client.
I am using this example :
Server:
host="my_ip"
port=4446
from socket import *
s=socket()
s.bind((host,port))
s.listen(1)
print "Listening for connections.. "
q,addr=s.accept()
var = 1
while var == 1 :
data=raw_input("Enter data to be send: ")
q.send(data)
s.close()
Client:
host="my_ip"
port=4446
from socket import *
s=socket(AF_INET, SOCK_STREAM)
s.connect((host,port))
var = 1
while var == 1 :
msg=s.recv(1024)
print "Message from server : " + msg
#response = "Message delivered" # Response to be send
#s.sendto(response(host,port))
s.close()
Python actual has a built in class to make your life a bit easier. http://docs.python.org/2/library/socketserver.html. I'm not sure I understand the second part of your question however; you can simply send data back to the server in the same way you had the server send data to the client.
Use sock.sendall(). Also, you shouldn't just name a var "var" as it doesn't describe what it does. I would create a boolean instead and name it something like, "isListening" or "isSending".
I have just started learning python and i was wondering how i would get the client to execute a function on the server and get some response
Here is my server code
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5)
while True:
connection, address = serversocket.accept()
buf = connection.recv(64)
if len(buf)> 0:
print(buf)
break
input('press enter')
This is the client code
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
data = 'lorem ipsum'
clientsocket.send(data.encode())
input('press enter')
and this is the function
def addme(x,y):
return x + y
print (addme(6,4))
Supposing i have the function addme() on the server,would it be possible to call it from the client and the response displayed to the client?.
If you simply want to call functions you should check out XMLRPC. Simple and easy, here's the example from the python documentation.
# Server code
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
def is_even(n):
return n%2 == 0
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.serve_forever()
# Client code
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
print "3 is even: %s" % str(proxy.is_even(3))
print "100 is even: %s" % str(proxy.is_even(100))
You'd have to send it some sort of message telling the server to execute this. For example you could send it a string "ADDME", when the server receives this, it stores addme()'s result and sends it back to the client which then prints it.
You need to set up your own communication protocol. Invent a command that, when you send it, makes the server execute some function.
To send data over a socket (comparable to a file-like object) you need to serialize (encode) it into a set of bytes, and, after receiving these bytes on the other end, deserialize (decode) those.
Encode the function's return value to e.g. JSON in case it is dictionary, to str in case it is an integer, or invent your own binary protocol or, if you would like to be able to send almost any kind of Python object through "the wire", then pickle the return value. Send the encoded (pickled) return value to the client. It has to decode (unpickle) it then.
In any case, you will have to implement your own protocol, with its own set of commands, while each command might have arguments. You will have to find a way to separate the command from its argument and will have to (in)validate commands you receive.
For learning network communication, your task is great. For implementing a production software, you must have a look and rock-solid messaging libraries such as xmlrpclib as pointed out by others.
Sounds like you are trying to implement RPC. See here for a discussion on existing libraries: What is the current choice for doing RPC in Python?
This is how i did it
server.py
from xmlrpc.server import SimpleXMLRPCServer
def addme(x,y):
return x + y
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(addme, "addme")
server.serve_forever()
input('press enter')
client.py
import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
print("the sum: %s" % str(proxy.addme(6,4)))
input('press enter')
I wanted to create a python script to stress test my servers.
So I created this basic UDP flooder and I think I have it working correctly.
My question is how would I go about adding multi-threading to this?
I read a manual on Python threading but didn't understand how to actually
implement it into my script.
import socket
import random
print "Target:",
ipaddr = raw_input()
sent = 1
bytes = random._urandom(10000)
port = 1
while sent > 0:
print "Test Started On", ipaddr, "|", sent, "Packets Sent. Press Ctrl+C To Stop."
sent += 1
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(bytes,(ipaddr,port))
port = random.randint(1, 65500)
raw_input()
If you extract the business part of your application into a function like:
def do_the_flooding():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(bytes,(ipaddr,port))
You can then call it in a thread:
import threading
t = threading.Thread(target=do_the_flooding)
t.start()