// tcpServer.java by fpont 3/2000
// usage : java tcpServer
1<port number="">.
2// default port is 1500.
3// connection to be closed by client.
4// this server handles only 1 connection.
5
6import java.net.*;
7import java.io.*;
8
9public class tcpServer {
10
11public static void main(String args[]) {
12
13int port;
14ServerSocket server_socket;
15BufferedReader input;
16try {
17port = Integer.parseInt(args[0]);
18}
19catch (Exception e) {
20System.out.println("port = 1500 (default)");
21port = 1500;
22}
23
24try {
25server_socket = new ServerSocket(port);
26System.out.println("Server waiting for client on port " +
27server_socket.getLocalPort());
28// server infinite loop
29while(true) {
30Socket socket = server_socket.accept();
31System.out.println("New connection accepted " +
32socket.getInetAddress() +
33":" + socket.getPort());
34input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
35// print received data
36try {
37while(true) {
38String message = input.readLine();
39if (message==null) break;
40System.out.println(message);
41}
42}
43catch (IOException e) {
44System.out.println(e);
45}
46
47// connection closed by client
48try {
49socket.close();
50System.out.println("Connection closed by client");
51}
52catch (IOException e) {
53System.out.println(e);
54}
55}
56}
57catch (IOException e) {
58System.out.println(e);
59}
60}
61}
62
63
64
65
66
67// tcpClient.java by fpont 3/2000
68
69// usage : java tcpClient <server> <port>
70// default port is 1500
71
72import java.net.*;
73import java.io.*;
74
75public class tcpClient {
76
77
78
79public static void main(String[] args) {
80
81int port = 1500;
82String server = "localhost";
83Socket socket = null;
84String lineToBeSent;
85BufferedReader input;
86PrintWriter output;
87int ERROR = 1;
88
89// read arguments
90if(args.length == 2) {
91server = args[0];
92try {
93port = Integer.parseInt(args[1]);
94}
95catch (Exception e) {
96System.out.println("server port = 1000 (default)");
97port = 1500;
98}
99}
100
101
102
103// connect to server
104try {
105socket = new Socket(server, port);
106System.out.println("Connected with server " +
107socket.getInetAddress() +
108":" + socket.getPort());
109}
110catch (UnknownHostException e) {
111System.out.println(e);
112System.exit(ERROR);
113}
114catch (IOException e) {
115System.out.println(e);
116System.exit(ERROR);
117}
118
119
120
121try {
122input = new BufferedReader(new InputStreamReader(System.in));
123output = new PrintWriter(socket.getOutputStream(),true);
124
125// get user input and transmit it to server
126while(true) {
127lineToBeSent = input.readLine();
128// stop if input line is "."
129if(lineToBeSent.equals(".")) break;
130output.println(lineToBeSent);
131}
132}
133catch (IOException e) {
134System.out.println(e);
135}
136
137try {
138socket.close();
139}
140catch (IOException e) {
141System.out.println(e);
142}
143}
144}</port></server></port>