mojo's Blog
명품 JAVA Programming 제 15장 실습문제 (1, 4, 7, 8 제외) 본문
2번 Code
Server Code
package Part15;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
public class ServerEx {
private static BufferedReader in = null;
private static BufferedWriter out = null;
private static ServerSocket listener = null;
private static Socket socket = null;
private static Scanner scanner = new Scanner(System.in);
private static MyThread mt;
class MyThread implements Runnable{
private boolean flag = false;
public void connect() {
flag = true;
}
public boolean getFlag() {
return flag;
}
public void run() {
int x=0;
while(x < 20) {
try {
Thread.sleep(500);
if(flag == true) {
out.write(x +"\n");
out.flush();
x++;
}
} catch(InterruptedException | IOException e) { return; }
}
flag = false;
}
}
ServerEx(){
mt = new MyThread();
Thread th = new Thread(mt);
th.start();
}
public static void main(String[] args) {
new ServerEx();
try {
System.out.println("타임서버입니다.");
listener = new ServerSocket(9999);
socket = listener.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
mt.connect();
System.out.println("연결되었습니다.");
System.out.println("500ms마다 수를 보냅니다.");
while(true) {
String inputMessage = in.readLine();
if(inputMessage.equalsIgnoreCase("disconnect")) {
System.out.println("접속을 종료합니다.");
break;
}
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
finally {
try {
scanner.close();
socket.close();
listener.close();
} catch(IOException e) {
System.out.println("클라이언트와 채팅 중 오류가 발생했습니다.");
}
}
}
}
Client Code
package Part15;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
public class ClientEx {
private static BufferedReader in = null;
private static BufferedWriter out = null;
private static Socket socket = null;
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
try {
socket = new Socket("localhost", 9999);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("서버에 접속하였습니다...");
System.out.print("서버의 시간 : ");
int cnt = 0;
while(cnt < 20) {
String inputMessage = in.readLine();
System.out.print(inputMessage + " ");
cnt++;
}
out.write("disconnect\n");
out.flush();
} catch(IOException e) {
System.out.println(e.getMessage());
}
finally {
try {
System.out.println("연결을 종료합니다.");
scanner.close();
socket.close();
} catch(IOException e) {
System.out.println("클라이언트와 채팅 중 오류가 발생했습니다.");
}
}
}
}
Program을 작성해서 Server 측에서 종료되지 못한 경우 해결방법
1. netstat -ano 입력
2. 위 코드에서는 9999번 포트를 설정하였으므로 9999번 포트에 해당하는 프로세스 아이디(PID) 를 찾는다.
3. 해당 프로세스 아이디를 kill 한다. => taskkill /f /pid 프로세스 아이디
3번 Code
Server Code
package Part15;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
public class ServerEx {
private static BufferedReader in = null;
private static BufferedWriter out = null;
private static ServerSocket listener = null;
private static Socket socket = null;
private static Scanner scanner = new Scanner(System.in);
public static String calc(String s) {
String ret="";
StringTokenizer st = new StringTokenizer(s);
if(st.countTokens() != 3) ret = "잘못된 연산";
int op1 = Integer.parseInt(st.nextToken());
String opcode = st.nextToken();
int op2 = Integer.parseInt(st.nextToken());
switch(opcode){
case "+": ret = Integer.toString(op1 + op2);
break;
case "-": ret = Integer.toString(op1 - op2);
break;
case "*": ret = Integer.toString(op1 * op2);
break;
default : ret = "잘못된 연산";
}
return ret;
}
public static void main(String[] args) {
try {
listener = new ServerSocket(9999);
socket = listener.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("클라이언트 연결됨");
while(true) {
String inputMessage = in.readLine();
if(inputMessage.equalsIgnoreCase("bye")) {
System.out.println("접속을 종료합니다.");
break;
}
String result = calc(inputMessage);
System.out.println(inputMessage+ " = " + result);
out.write(result + "\n");
out.flush();
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
finally {
try {
System.out.println("프로그램을 종료합니다.");
scanner.close();
socket.close();
listener.close();
} catch(IOException e) {
System.out.println("클라이언트와 채팅 중 오류가 발생했습니다.");
}
}
}
}
Client Code
package Part15;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
public class ClientEx extends JFrame {
private static BufferedReader in = null;
private static BufferedWriter out = null;
private static Socket socket = null;
private static Scanner scanner = new Scanner(System.in);
private static JTextField []tf = new JTextField[3];
private JLabel jl = new JLabel("=");
private static JTextField resTf = new JTextField(6);
private JButton jb = new JButton("계산");
ClientEx(){
setTitle("14장 연습하기");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
tf[0] = new JTextField(6);
tf[1] = new JTextField(2);
tf[2] = new JTextField(6);
c.add(tf[0]); c.add(tf[1]); c.add(tf[2]);
c.add(jl);
c.add(resTf);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(tf[0].getText().equals("bye")) {
try {
out.write("bye\n");
out.flush();
scanner.close();
socket.close();
System.exit(0);
} catch(IOException e2) {
System.out.println("클라이언트와 채팅 중 오류가 발생했습니다.");
}
}
else {
String ret = tf[0].getText()+" "+tf[1].getText()+" "+tf[2].getText();
try {
out.write(ret+"\n");
out.flush();
} catch (IOException e1) {
System.out.println(e1.getMessage());
}
}
}
});
c.add(jb);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
try {
socket = new Socket("localhost", 9999);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
new ClientEx();
while(true) {
String inputMessage = in.readLine();
resTf.setText(inputMessage);
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
5번 Code
Server Code
package Part15;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
class Score{
private String name, score;
Score(String name, String score){
this.name = name;
this.score = score;
}
String getName() {
return name;
}
String getScore() {
return score;
}
}
public class ServerEx {
private static BufferedReader in = null;
private static BufferedWriter out = null;
private static ServerSocket listener = null;
private static Socket socket = null;
private static Scanner scanner;
private static Vector<Score> v = new Vector<Score>();
public static void setScore() {
try {
scanner=new Scanner(new FileReader("C:\\Temp\\score.txt"));
while(scanner.hasNext()){
String word=scanner.nextLine();
String []score = word.split(" ");
v.add(new Score(score[0], score[1]));
}
System.out.println("score.txt 읽기 완료");
} catch(IOException e) {
System.out.println("입출력 오류");
}
}
public static String getResult(String name) {
String ret = "없는 이름";
for(int i=0; i<v.size(); i++) {
if(name.equals(v.get(i).getName())) {
ret = v.get(i).getScore();
}
}
return ret;
}
public static void main(String[] args) {
setScore();
scanner = new Scanner(System.in);
try {
listener = new ServerSocket(9999);
socket = listener.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("클라이언트 연결됨");
while(true) {
String inputMessage = in.readLine();
if(inputMessage.equalsIgnoreCase("bye")) {
System.out.println("접속을 종료합니다.");
break;
}
String result = getResult(inputMessage);
System.out.println(inputMessage+ " : " + result);
out.write(result + "\n");
out.flush();
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
finally {
try {
System.out.println("프로그램을 종료합니다.");
scanner.close();
socket.close();
listener.close();
} catch(IOException e) {
System.out.println("클라이언트와 채팅 중 오류가 발생했습니다.");
}
}
}
}
Client Code
package Part15;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
public class ClientEx extends JFrame {
private static BufferedReader in = null;
private static BufferedWriter out = null;
private static Socket socket = null;
private static Scanner scanner = new Scanner(System.in);
private static JLabel resJl = new JLabel(" ");
private JTextField tf = new JTextField(7);
ClientEx(){
setTitle("14장 연습하기");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
c.add(new JLabel("이름 입력"));
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField jtf = (JTextField)(e.getSource());
String s = jtf.getText();
try {
out.write(s+"\n");
out.flush();
if(s.equals("bye")) System.exit(0);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
c.add(tf);
c.add(new JLabel("성적"));
c.add(resJl);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
try {
socket = new Socket("localhost", 9999);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
new ClientEx();
while(true) {
String inputMessage = in.readLine();
resJl.setText(inputMessage);
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
6번 Code
Server Code
package Part15;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
class Word {
private String eng, han;
Word(String eng, String han){
this.eng = eng;
this.han = han;
}
String getEng() {
return eng;
}
String getHan() {
return han;
}
}
public class ServerEx extends JFrame {
private static BufferedReader in = null;
private static BufferedWriter out = null;
private static ServerSocket listener = null;
private static Socket socket = null;
private static Scanner scanner = new Scanner(System.in);
private static Vector<Word> v = new Vector<Word>();
private String []ls = {"영어", "한글"};
private JTextField []tf = new JTextField[2];
private String []bs = {"저장", "찾기"};
private JButton []btn = new JButton[2];
private JTextArea ta = new JTextArea(7,25);
public static String getResult(String eng) {
String ret = "없는 단어";
for(int i=0; i<v.size(); i++) {
if(eng.equals(v.get(i).getEng())) {
ret = v.get(i).getHan();
}
}
return ret;
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton)(e.getSource());
if(jb.getText().equals("저장")) {
String eng = tf[0].getText(), han = tf[1].getText();
v.add(new Word(eng, han));
ta.setText(ta.getText()+"삽입 ("+eng+", "+han+")\n");
}
else {
String res = getResult(tf[0].getText());
tf[1].setText(res);
ta.setText(ta.getText()+"검색 ("+tf[0].getText()+")\n");
}
}
}
ServerEx(){
setTitle("14장 연습하기");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
for(int i=0; i<2; i++) {
c.add(new JLabel(ls[i]));
tf[i] = new JTextField(10);
c.add(tf[i]);
}
for(int i=0; i<2; i++) {
btn[i] = new JButton(bs[i]);
btn[i].addActionListener(new MyActionListener());
c.add(btn[i]);
}
ta.setText("");
c.add(new JScrollPane(ta));
setSize(350, 300);
setVisible(true);
}
public static void main(String[] args) {
try {
listener = new ServerSocket(9999);
socket = listener.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
new ServerEx();
while(true) {
String inputMessage = in.readLine();
if(inputMessage.equalsIgnoreCase("bye")) {
System.out.println("접속을 종료합니다.");
break;
}
String result = getResult(inputMessage);
System.out.println("Ok~!");
out.write(result + "\n");
out.flush();
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
finally {
try {
scanner.close();
socket.close();
listener.close();
} catch(IOException e) {
System.out.println("클라이언트와 채팅 중 오류가 발생했습니다.");
}
}
}
}
Client Code
package Part15;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
public class ClientEx extends JFrame {
private static BufferedReader in = null;
private static BufferedWriter out = null;
private static Socket socket = null;
private static Scanner scanner = new Scanner(System.in);
private String ls[] = {"영어", "한글"};
private static JTextField tf[] = new JTextField[2];
private JButton btn = new JButton("찾기");
ClientEx(){
setTitle("14장 연습하기");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
for(int i=0; i<2; i++) {
c.add(new JLabel(ls[i]));
tf[i] = new JTextField(7);
c.add(tf[i]);
}
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String eng = tf[0].getText();
try {
out.write(eng + "\n");
out.flush();
if(eng.equals("bye")) System.exit(0);
} catch(IOException e1) {
System.out.println(e1.getMessage());
}
}
});
c.add(btn);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
try {
socket = new Socket("localhost", 9999);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
new ClientEx();
while(true) {
String inputMessage = in.readLine();
tf[1].setText(inputMessage);
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
'Java' 카테고리의 다른 글
JDBC Programming (0) | 2021.08.24 |
---|---|
데이터베이스 (0) | 2021.08.24 |
명품 JAVA Programming 제 15장 Open Challenge (0) | 2021.08.23 |
수식 계산 Server-Client 만들기 (0) | 2021.08.23 |
Server-Client Chatting Program 만들기 (0) | 2021.08.23 |
Comments