-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathServer.java
96 lines (76 loc) · 2.89 KB
/
Server.java
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
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/** TCP/IP Server Socket
* Network Programming
*
* @author Kitkat
*
*/
public class Server {
private static final String Naver = "www.naver.com";
private static ServerSocket serverSocket;
private static Socket socket;
public static void main(String[] args) {
ipAddress();
try {
// Instantiate ServerSocket Class
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(2800));
// Connection Wait for Multiple Client
while(true) {
System.out.println("Connetion wait..");
socket = serverSocket.accept();
InetSocketAddress isa = (InetSocketAddress) socket.getRemoteSocketAddress();
System.out.println("Connection Accepted! Client [" + isa.getHostName() + ":" + isa.getPort() + "]");
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
byte[] byteArr = new byte[512];
String msg = null;
int readByteCount = is.read(byteArr);
if(readByteCount == -1)
throw new IOException();
msg = new String(byteArr, 0, readByteCount, "UTF-8");
System.out.println("Data Received OK!");
System.out.println("Message : " + msg);
msg = "Hello Client";
byteArr = msg.getBytes("UTF-8");
os.write(byteArr);
System.out.println("Data Transmitted OK!");
os.flush();
is.close();
os.close();
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try { socket.close(); } catch (IOException e1) { e1.printStackTrace(); }
}
if(!serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void ipAddress() {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("LocalHost IP Address : " + inetAddress.getHostAddress());
InetAddress[] iaArr = InetAddress.getAllByName(Naver);
for(InetAddress ia : iaArr)
System.out.println(Naver + " IP Address : " + ia.getHostAddress());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}