-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTCPServer.java
More file actions
82 lines (77 loc) · 1.84 KB
/
TCPServer.java
File metadata and controls
82 lines (77 loc) · 1.84 KB
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
/**
* TCPServer.java
*
* This is a minimal TCPServer that reads strings from the socket
* and echo the same string back to the client.
*
* This demo illustrates how to use ServerSocket class and Socket
* class.
*
* Author: Ooi Wei Tsang (ooiwt@comp.nus.edu.sg)
*/
import java.net.*;
import java.io.*;
class TCPServer {
public static void main(String args[]) throws Exception
{
ServerSocket serverSocket;
try
{
// Listen on port 2105 for incoming connections.
serverSocket = new ServerSocket(2105);
}
catch (IOException e)
{
System.err.println("Unable to listen on port 2105: " + e.getMessage());
return;
}
// Repeatedly accepts connection from clients until the server is killed.
while (true)
{
Socket socket;
try
{
// Wait for a connection to come
socket = serverSocket.accept();
System.out.println("connection accepted\n");
}
catch (IOException e)
{
System.err.println("Unable to accept connection on port 2105: " + e.getMessage());
return;
}
// Connection accepted. Now, get the input/output stream
// so that we can read from/write into the socket.
try
{
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
// Repeatedly read a line from the socket and echo
// it back to the socket.
while (true)
{
String line = br.readLine();
if (line == null)
{
socket.close();
break;
}
if (line.equals("bye"))
{
socket.close();
break;
}
dos.writeBytes(line + "\n");
dos.flush();
}
}
catch (IOException e)
{
System.err.println("Unable to read/write on socket: " + e.getMessage());
return;
}
}
}
}