네크워크란 컴퓨터끼리 데이터를 주고 받는 시스템이다.
각 층마다 수행하는 역할이 다르다.
https://www.codetextpro.com/2019/07/networking-socket-program.html
public class SocketClientSample {
public static void main(String[] args) {
SocketClientSample sample = new SocketClientSample();
sample.sendSocketSample();
}
private void sendSocketSample() {
for (int i = 0; i < 4; i++) {
sendSocketData("I liked java at " + new Date());
}
sendSocketData("EXIT");
}
private void sendSocketData(String s) {
Socket socket = null;
try{
System.out.println("Client:connection");
socket = new Socket("127.0.0.1", 9999);
System.out.println("Client: Connect status = " + socket.isConnected());
Thread.sleep(1000);
OutputStream stream = socket.getOutputStream();
BufferedOutputStream out = new BufferedOutputStream(stream);
byte[] bytes = s.getBytes();
out.write(bytes);
System.out.println("Client: Sent data");
out.close();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
public class SocketServerSample {
public static void main(String[] args) throws IOException {
SocketServerSample sample = new SocketServerSample();
sample.startServer();
}
private void startServer() {
ServerSocket server = null;
Socket client = null;
try {
server = new ServerSocket(9999);
while (true){
System.out.println("SERVER WAITING FOR REQUEST...");
client = server.accept();
System.out.println("Server: Accepted.");
InputStream stream = client.getInputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(stream)
);
String data = null;
StringBuilder receivedData = new StringBuilder();
while ((data = in.readLine()) != null) {
receivedData.append(data);
}
System.out.println("Received Data: " +receivedData);
in.close();
stream.close();
client.close();
if (receivedData!=null && "EXIT".equals(receivedData.toString())){
System.out.println("Stop SocketServer");
break;
}
System.out.println("----------------------------------");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) {
try{
server.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}