kh18일차(Server연결 TCP/DNS서버연결, 이를이용한 baseball게임)
2022. 7. 13. 18:02ㆍ코딩/Java
TCPServer/DnsServer/baseballgame
package kh.java.func;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
public class TcpServer {
public void tcpServer() {
Scanner sc = new Scanner(System.in);
// 1.서버에서 사용할 포트번호 지정
// 0~66535번호 사이에 1개를 사용
// 0~1000 사이 번호는 사용중인 번호가 많으므로 1000번이후를 사용
int port = 9999;
// 반환할 객체미리 선언
// 서버에서 포트를 열기위한객체
ServerSocket server = null; // 접속대기를 해주는 친구
// 데이터 주고받기위한 보조스트림
DataOutputStream dos = null;
DataInputStream dis = null;
try {
// 2. 서버소켓객체생성
// 생성자 매개변수로 전달한 포트번호가 열리면서 서버 대기상태
server = new ServerSocket(port);
System.out.println("[서버 준비 완료]");
System.out.println("클라이언트 접속 요청 대기중.....");
// 3. server.accept();클라이언트 접속요청대기
// 4.접속요청이 들오오면 수락해서 통신할 객체를 생성
Socket client = server.accept();// 클라이언트로 넘어감//둘사이 소켓이 만들어짐
System.out.println("클라이언트 접속 완료");
while (true) {
// 5.데이터를 주고받기위한 스트림 추출
// 소켓안에 이미 스트림이 존재(양방향)
OutputStream out = client.getOutputStream();
InputStream in = client.getInputStream();
// 6.보조스트림으로 성능향상
dos = new DataOutputStream(out);
dis = new DataInputStream(in);
// 7.스트림을 통한 입력및 출력
String clientMsg = dis.readUTF();// 클라이언트에서 온 메세지를 저장
if (clientMsg.equals("exit")) {
break;
} else {
System.out.println(clientMsg);// 저장한 메세지 출력
}
System.out.print("클라이언트에 전송할 메세지 : ");
String sendMsg = sc.nextLine();
if (sendMsg.equals("exit")) {
dos.writeUTF(sendMsg);
break;
} else {
dos.writeUTF(sendMsg);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 8.사용한자원 반환
try {
dis.close();
dos.close();
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void DnsServer() {
Scanner sc = new Scanner(System.in);
int port = 8888;
int num1 = 0;
ServerSocket server = null;
DataOutputStream dos = null;
DataInputStream dis = null;
HashMap<String, String> domain = new HashMap<String, String>();
domain.put("www.naver.com", "125.209.222.142");
domain.put("www.google.com", "172.217.175.4");
domain.put("www.iei.or.kr", "211.43.14.187");
try {
server = new ServerSocket(port);
System.out.println("[서버 준비 완료]");
while (true) {
System.out.println("클라이언트 요청 대기중.....");
Socket client = server.accept();// 둘다이 소켓이 만들어짐
OutputStream out = client.getOutputStream();
InputStream in = client.getInputStream();// 소켓의 내용물을 꺼내는것
dos = new DataOutputStream(out);
dis = new DataInputStream(in);
String clientMsg = dis.readUTF();
if (domain.containsKey(clientMsg)) {
num1++;
// System.out.println(clientMsg);
String sendMsg = domain.get(clientMsg);
// System.out.println(sendMsg);
dos.writeUTF(clientMsg + "의 주소는" + sendMsg + "입니다");
} else {
num1++;
String sendMsg = "주소가없습니다.";
dos.writeUTF(sendMsg);
}
System.out.println("요청" + num1 + "건 처리 완료");
System.out.println("서버를 종료 하시겠습니까 [y/n]");
String str = sc.nextLine();
if (str.equals("y")) {
break;
} else if (str.equals("n")) {
continue;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
dos.close();
dis.close();
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void baseballGame() {
Scanner sc = new Scanner(System.in);
Random r = new Random();
// HashMap<Integer, Integer> baseball = new HashMap<Integer, Integer>();
int port = 8899;
int random[] = new int[3];
ServerSocket server = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
server = new ServerSocket(port);
System.out.println("서버 준비 완료");
while (true) {
int num1 = 0;
Socket client = server.accept();
OutputStream out = client.getOutputStream();
InputStream in = client.getInputStream();
dos = new DataOutputStream(out);
dis = new DataInputStream(in);
for (int i = 0; i < 3; i++) {
// baseball.put(i,r.nextInt(10));
random[i] = r.nextInt(10);
for (int j = 0; j < i; j++) {
if (random[i] == random[j]) {
i--;
break;
}
}
}
System.out.println(random[0]);
System.out.println(random[1]);
System.out.println(random[2]);
while (true) {
System.out.println("클라이언트 숫자입력 대기중");
int clientMsg1 = dis.readInt();
int clientMsg2 = dis.readInt();
int clientMsg3 = dis.readInt();
System.out.println("클라이언트가 입력한 숫자" + clientMsg1 + " " + clientMsg2 + " " + clientMsg3);
if(clientMsg1 == clientMsg2 || clientMsg1 == clientMsg3 || clientMsg2 == clientMsg3) {
System.out.println("중복된 숫자가 있습니다. 다시 입력해 주세요.");
dos.writeUTF("중복된 숫자가 있습니다. 다시 입력해 주세요.");
continue;
}
int s = 0;
int b = 0;
num1++;
if (random[0] == clientMsg1) {
s++;
} else if (random[1] == clientMsg1) {
b++;
} else if (random[2] == clientMsg1) {
b++;
}
if (random[0] == clientMsg2) {
b++;
} else if (random[1] == clientMsg2) {
s++;
} else if (random[2] == clientMsg2) {
b++;
}
if (random[0] == clientMsg3) {
b++;
} else if (random[1] == clientMsg3) {
b++;
} else if (random[2] == clientMsg3) {
s++;
}
System.out.println("스트라이크" + s + "개 볼" + b + "개");
dos.writeUTF("스트라이크" + s + "개 볼" + b + "개");
if (s == 3) {
break;
}
if (num1 == 9) {
dos.writeUTF("10회동안 맞추지 못했습니다 정답은." + random[0] + " " + random[1] + " " + random[2] + "입니다");
break;
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
dos.close();
dis.close();
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
TCPClient/DnsClient
package kh.java.func;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TcpClient {
public void tcpClient() {
Scanner sc = new Scanner(System.in);
// 1.서버 아이피 주소, 포트번호지정
String serverIp = "127.0.0.1";// 자기자신아이피호출(루프백)
int serverPort = 9999;// 서버에서 사용하는 포트번호
// 자원반환에 필요한 객체 미리선언
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
socket = new Socket(serverIp, serverPort);
System.out.println("서버접속완료!!!");
while (true) {
// 3.데이터를 주고받기위한 스트림을 추출
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// 4.보조스트림을 통한 성능개선
dis = new DataInputStream(in);
dos = new DataOutputStream(out);
// 5.스트림을 통한 입력 또는 출력진행
System.out.print("서버에 전송할 메세지 : ");
String sendMsg = sc.nextLine();
if (sendMsg.equals("exit")) {
dos.writeUTF(sendMsg);// 메세지 서버로 보내기
break;
} else {
dos.writeUTF(sendMsg);// 메세지 서버로 보내기
}
String severMsg = dis.readUTF();
if (severMsg.equals("exit")) {
break;
} else {
System.out.println(severMsg);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 6.사용 자원반환
try {
dos.close();
dis.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void DnsClient() {
Scanner sc = new Scanner(System.in);
String serverIp = "127.0.0.1";
int serverPort = 8888;
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
socket = new Socket(serverIp, serverPort);//소켓에 accept할 객체 생성
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
dis = new DataInputStream(in);
dos = new DataOutputStream(out);
System.out.print("전송할 메세지 입력 : ");
String sendMsg = sc.nextLine();
dos.writeUTF(sendMsg);// 메세지 서버로 보내기
String serverMsg = dis.readUTF();
System.out.println(serverMsg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
dis.close();
dos.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void multiClient() {
String serverIp = "192.168.10.96";// 자기자신아이피호출(루프백)
int serverPort = 8989;// 서버에서 사용하는 포트번호
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
Scanner sc = new Scanner(System.in);
socket = new Socket(serverIp, serverPort);
System.out.println("서버 접속 완료!");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
dis = new DataInputStream(in);
dos = new DataOutputStream(out);
System.out.print("서버에 전송할 메세지 : ");
String sendMsg = sc.nextLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
'코딩 > Java' 카테고리의 다른 글
다이나믹 웹 프로젝트 진행순서,방식 (0) | 2022.09.04 |
---|---|
kh17일차 InputOutput(WordContorller) (0) | 2022.07.12 |
kh16일차(set,map,PointMgr7,StudentMgr5,Exception,io) (0) | 2022.07.11 |
kh15일차 (Generics,List,studentMgr4,pointMgr5...) (0) | 2022.07.08 |
kh14일차 (0) | 2022.07.07 |