1
+ package sporadic .socket_programming ;
2
+
3
+ import java .io .DataInputStream ;
4
+ import java .io .DataOutputStream ;
5
+ import java .io .IOException ;
6
+ import java .net .ServerSocket ;
7
+ import java .net .Socket ;
8
+ import java .net .SocketTimeoutException ;
9
+
10
+ // TODO: this program not working yet, make it work or start from scratch to write another socket
11
+ // program to better understand socket.
12
+
13
+ /**
14
+ * Compile client and server and then start server as follows:
15
+ *
16
+ * $ java GreetingServer 6066 Waiting for client on port 6066... Check client
17
+ * program as follows:
18
+ *
19
+ * $ java GreetingClient localhost 6066 Connecting to localhost on port 6066
20
+ * Just connected to localhost/127.0.0.1:6066 Server says Thank you for
21
+ * connecting to /127.0.0.1:6066 Goodbye!
22
+ *
23
+ * But it's not working as above, running from Eclipse and from terminal,
24
+ * neither worked. I'll have to figure out why it didn't work and make it work
25
+ * in the future./
26
+ *
27
+ * /** The following GreetingServer program is an example of a server
28
+ * application that uses the Socket class to listen for clients on a port number
29
+ * specified by a command-line argument:
30
+ */
31
+ public class GreetingServer extends Thread {
32
+ private ServerSocket serverSocket ;
33
+
34
+ public GreetingServer (int port ) throws IOException {
35
+ serverSocket = new ServerSocket (port );
36
+ serverSocket .setSoTimeout (10000 );
37
+ }
38
+
39
+ public void run () {
40
+ while (true ) {
41
+ try {
42
+ System .out .println ("Waiting for client on port "
43
+ + serverSocket .getLocalPort () + "..." );
44
+ Socket server = serverSocket .accept ();
45
+ System .out .println ("Just connected to "
46
+ + server .getRemoteSocketAddress ());
47
+ DataInputStream in = new DataInputStream (
48
+ server .getInputStream ());
49
+ System .out .println (in .readUTF ());
50
+ DataOutputStream out = new DataOutputStream (
51
+ server .getOutputStream ());
52
+ out .writeUTF ("Thank you for connecting to "
53
+ + server .getLocalSocketAddress () + "\n Goodbye!" );
54
+ server .close ();
55
+ } catch (SocketTimeoutException s ) {
56
+ System .out .println ("Socket timed out!" );
57
+ break ;
58
+ } catch (IOException e ) {
59
+ e .printStackTrace ();
60
+ break ;
61
+ }
62
+ }
63
+ }
64
+
65
+ public static void main (String [] args ) {
66
+ int port = Integer .parseInt (args [0 ]);
67
+ try {
68
+ Thread t = new GreetingServer (port );
69
+ t .start ();
70
+ } catch (IOException e ) {
71
+ e .printStackTrace ();
72
+ }
73
+ }
74
+ }
0 commit comments