Example Client program using TCP public class Tclient final static Str

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/**
* Example Client program using TCP.
*/
public class Tclient {
final static String serverIPname = "minnie.williams.org"; // server IP name
final static int serverPort = 3456; // server port number
public static void main(String args[]) {
java.net.Socket sock = null; // Socket object for communicating
java.io.PrintWriter pw = null; // socket output to server
java.io.BufferedReader br = null; // socket input from server
try {
sock = new java.net.Socket(serverIPname,serverPort); // create socket and connect
pw = new java.io.PrintWriter(sock.getOutputStream(), true); // create reader and writer
br = new java.io.BufferedReader(new java.io.InputStreamReader(sock.getInputStream()));
System.out.println("Connected to Server");
pw.println("Message from the client"); // send msg to the server
System.out.println("Sent message to server");
String answer = br.readLine(); // get data from the server
System.out.println("Response from the server >" + answer);
pw.close(); // close everything
br.close();
sock.close();
} catch (Throwable e) {
System.out.println("Error " + e.getMessage());
e.printStackTrace();
}
}
}
/**
* Example Server program using TCP.
*/
public class Tserver {
final static int serverPort = 3456; // server port number
public static void main(String args[]) {
java.net.ServerSocket sock = null; // original server socket
java.net.Socket clientSocket = null; // socket created by accept
java.io.PrintWriter pw = null; // socket output stream
java.io.BufferedReader br = null; // socket input stream
try {
sock = new java.net.ServerSocket(serverPort); // create socket and bind to port
System.out.println("waiting for client to connect");
clientSocket = sock.accept(); // wait for client to connect
System.out.println("client has connected");
pw = new java.io.PrintWriter(clientSocket.getOutputStream(),true);
br = new java.io.BufferedReader(
new java.io.InputStreamReader(clientSocket.getInputStream()));
String msg = br.readLine(); // read msg from client
System.out.println("Message from the client >" + msg);
pw.println("Got it!"); // send msg to client
pw.close(); // close everything
br.close();
clientSocket.close();
sock.close();
} catch (Throwable e) {
System.out.println("Error " + e.getMessage());
e.printStackTrace();
}
}
}