Hide
Stay up to dateembedded code automagically updates, each snippet and article has a feed Join Siafoo Now or Learn More

Java sockets based Client/Server application Atom Feed 0

In Brief An example of using Java Sockets inside a Scala application.
# 's
  1import java.io._
2import java.net.{InetAddress,ServerSocket,Socket,SocketException}
3import java.util.Random
4
5/**
6 * Simple client/server application using Java sockets.
7 *
8 * The server simply generates random integer values and
9 * the clients provide a filter function to the server
10 * to get only values they interested in (eg. even or
11 * odd values, and so on).
12 */
13object randomclient {
14
15 def main(args: Array[String]) {
16 val filter: Int => Boolean = try {
17 Integer.parseInt(args(0)) match {
18 case 1 => x: Int => x % 2 != 0
19 case 2 => x: Int => x % 2 == 0
20 case _ => x: Int => x != 0
21 }
22 }
23 catch {
24 case _ => x: Int => x < 100
25 }
26
27 try {
28 val ia = InetAddress.getByName("localhost")
29 val socket = new Socket(ia, 9999)
30 val out = new ObjectOutputStream(
31 new DataOutputStream(socket.getOutputStream()))
32 val in = new DataInputStream(socket.getInputStream())
33
34 out.writeObject(filter)
35 out.flush()
36
37 while (true) {
38 val x = in.readInt()
39 println("x = " + x)
40 }
41 out.close()
42 in.close()
43 socket.close()
44 }
45 catch {
46 case e: IOException =>
47 e.printStackTrace()
48 }
49 }
50
51}
52
53object randomserver {
54
55 def main(args: Array[String]): Unit = {
56 try {
57 val listener = new ServerSocket(9999);
58 while (true)
59 new ServerThread(listener.accept()).start();
60 listener.close()
61 }
62 catch {
63 case e: IOException =>
64 System.err.println("Could not listen on port");
65 System.exit(-1)
66 }
67 }
68
69}
70
71case class ServerThread(socket: Socket) extends Thread("ServerThread") {
72
73 override def run(): Unit = {
74 val rand = new Random(System.currentTimeMillis());
75 try {
76 val out = new DataOutputStream(socket.getOutputStream());
77 val in = new ObjectInputStream(
78 new DataInputStream(socket.getInputStream()));
79
80 val filter = in.readObject().asInstanceOf[Int => Boolean];
81
82 while (true) {
83 var succeeded = false;
84 do {
85 val x = rand.nextInt(1000);
86 succeeded = filter(x);
87 if (succeeded) out.writeInt(x)
88 } while (! succeeded);
89 Thread.sleep(100)
90 }
91
92 out.close();
93 in.close();
94 socket.close()
95 }
96 catch {
97 case e: SocketException =>
98 () // avoid stack trace when stopping a client with Ctrl-C
99 case e: IOException =>
100 e.printStackTrace();
101 }
102 }
103
104}

An example of using Java Sockets inside a Scala application.