JAVA.awt
other로 가서
여기서 table.sql로 이름 설정
그리고 sql 소스코드 복사해 넣으면 끝
package ch14;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
public class ChatServer2 {
ServerSocket server;
int port = 8003;
// Vector<저장시킬 데이터타입> : 제네릭
Vector<ClientThread2> vc;
public ChatServer2() {
try { // 서버 시작
server = new ServerSocket(port);
vc = new Vector<ClientThread2>();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error in Server");
// 1은 비정상적인 종료를 의미 ( 매개변수가 0이면 정상적인 종료) : 일반적으로사용
System.exit(1);
}
System.out.println("*ChatServer 2.0*********************");
System.out.println("*client 접속을 기다리고있습니다.****");
System.out.println("************************************");
try {
while(true) { // 무한반복문
Socket sock = server.accept();
ClientThread2 ct = new ClientThread2(sock);
ct.start(); // 쓰레드 스케쥴러에 등록 -> run 메소드 호출
vc.addElement(ct); // ClientThread 객체를 벡터에 저장
}
} catch (Exception e) {
System.err.println("Error in sock");
e.printStackTrace();
}
}
// 모든 접속된 Client에게 메세지 전달하는 메서드 sendAllMessage()
public void sendAllMessage(String msg) {
// A가 Vector로 묶인 서버에 "안녕" 보내면 A, B, C 모두에게 메세지가 가야함
for (int i = 0; i < vc.size(); i++) {
// Vector에 저장된 ClientThread를 순차적으로 가져옴
ClientThread2 ct = vc.get(i);
// ClientThread 가지고 있는 각각의 메세지 보내는 메소드 호출
// -> 모든 접속되어있는 클라이언트에게 동일한 메세지가 보내짐
ct.sendMessage(msg);
}
}
// 접속이 끊어진 ClientThread는 Vector에서 제거해줘야함
public void removeClient(ClientThread2 ct) {
vc.remove(ct);
}
// 접속된 모든 id 리스트 ex)aaa;bbb;ccc;강호동
public String getIds() {
String ids = "";
for(int i = 0; i < vc.size(); i++) {
ClientThread2 ct = vc.get(i);
ids += ct.id + ";";
}
return ids;
}
// 지정한 ClientThread2 검색
public ClientThread2 findClient(String id) { // ??
ClientThread2 ct = null;
for(int i = 0; i < vc.size(); i++) {
ct = vc.get(i);
if(id.equals(ct.id)) {
break; // 찾은거임(10개중에 3번째에서 찾았으면 나머지 7개는 볼 필요 없으니까)
}//--if
}//--for
return ct;
}
class ClientThread2 extends Thread{ // 내부클래스
Socket sock;
BufferedReader in;
PrintWriter out;
String id; // 사용자 id를 저장할 변수 id 생성
public ClientThread2(Socket sock) { // 생성자
// 반복사용 try - catch문
try {
this.sock = sock;
in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream(), true);
System.out.println(sock + "접속됨...");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
// Client가 처음으로 받는 메세지
out.println("사용하실 아이디를 입력하세요.");
while(true) {
String line = in.readLine();
if(line == null)
break;
else
routine(line);
}
in.close(); // 오류나는이유? 죽은 코드이기때문(절대 실행될수없는 코드)
out.close();
removeClient(this);
} catch (Exception e) { // 채팅 실행(run)중 문제가 생겼을때
removeClient(this); // 현재 객체 자신(Vector 내부의)
System.err.println(sock + "끊어짐...");
}
}
private void routine(String line) {
// CHATALL:[aaa]오늘은 월요일입니다. <- 프로토콜과 메세지를 짤라야함
System.out.println(line);
int idx = line.indexOf(ChatProtocol2.DM); // : (콜론)을 의미
String cmd = line.substring(0, idx); // 0부터 : 까지 = << CHATALL >>
String data = line.substring(idx + 1); // : 바로 뒤 위치부터 끝까지 = << [aaa]오늘은 월요일입니다. >>
if(cmd.equals(ChatProtocol2.ID)) {
id = data; // aaa
// 새로운 접속자가 추가 되었기 때문에 리스트 재전송 해야함
sendAllMessage(ChatProtocol2.CHATLIST + ChatProtocol2.DM + getIds());
// welcome 메세지 전송
sendAllMessage(ChatProtocol2.CHATALL + ChatProtocol2.DM + "[" + id + "]님이 입장하였습니다.");
} else if(cmd.equals(ChatProtocol2.CHAT)) {
// data : bbb;밥먹자 (받는아이디;메세지)
idx = data.indexOf(';'); // idx는 세미콜론(;) 의 위치값을 얻어옴
cmd = data.substring(0, idx); // bbb
data = data.substring(idx + 1); // data
ClientThread2 ct = findClient(cmd);
if(ct != null) { // 현재 접속자
// ct는 bbb 접속자
ct.sendMessage(ChatProtocol2.CHAT + ChatProtocol2.DM + "[" + id + "(S)]" + data);// CHAT:[aaa(S)]밥먹자
sendMessage(ChatProtocol2.CHAT + ChatProtocol2.DM + "[" + id + "(S)]" + data); // CHAT:[aaa(S)]밥먹자
// (S)는 귓속말 채팅이라는 걸 표시해주기 위해 넣음.
} else { // bbb가 접속이 안 된 경우
sendMessage(ChatProtocol2.CHAT + ChatProtocol2.DM + "[" + cmd + "]님 접속자가 아닙니다.");
}
} else if(cmd.equals(ChatProtocol2.MESSAGE)) {
idx = data.indexOf(';'); // idx는 세미콜론(;) 의 위치값을 얻어옴
cmd = data.substring(0, idx); // bbb
data = data.substring(idx + 1); // data
ClientThread2 ct = findClient(cmd);
if(ct != null) { // 현재 접속자
// ct는 bbb 접속자
ct.sendMessage(ChatProtocol2.MESSAGE + ChatProtocol2.DM + id + ';' + data);// CHAT:[aaa(S)]밥먹자
} else { // bbb가 접속이 안 된 경우(aaa가 bbb에게)
sendMessage(ChatProtocol2.CHAT + ChatProtocol2.DM + "[" + cmd + "]님 접속자가 아닙니다.");
}
} else if(cmd.equals(ChatProtocol2.CHATALL)) {
sendAllMessage(ChatProtocol2.CHATALL + ChatProtocol2.DM + "[" + id + "]" + data);
}
}//-- routine()
// Client 에게 메세지 전달 메소드
public void sendMessage(String msg) {
out.println(msg);
}
}
public static void main(String[] args) {
new ChatServer2();
}
}
package ch14;
public class ChatProtocol2 {
// (C->S) ID : aaa 프로토콜
// (S->C) CHALLIST : aaa; bbb; ccc; 강호동;
public static final String ID = "ID"; //앞에 프로토콜 붙여서 서버는 그것을 분석한다.
// (C->S) CHAT: 받는 아이디;메세지 ex)CHAT:bbb;밥먹자
// (S->C) CHAT: 보내는 아이디;메세지 ex)CHAT:aaa;밥먹자 //귓속말
public static final String CHAT = "CHAT";
// (C->S) CHATALL : 메세지
// (S->C) CHATALL : [보낸 아이디]메세지
public static final String CHATALL = "CHATALL";
// (C->S) MESSAGE : 받는 아이디;쪽지내용 ex)MESSAGE:bbb;지금어디?
// (S->C) MESSAGE : 보내는 아이디;쪽지내용 ex)MESSAGE:bbb;지금어디?
public static final String MESSAGE = "MESSAGE";
// (S->C) CHALLIST :aaa;bbb;ccc;강호동;
public static final String CHATLIST = "CHATLIST";
//구분지 -> 프로토콜:data(delimiter)delimeter
public static final String DM =":";
}
package ch14;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.List;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.StringTokenizer;
//여러 명이랑 채팅가능. 여기서 f11로 창 여러 개 띄우면 같이 대화 가능.
public class ChatClient2 extends MFrame //MFrame 상속안받으니까 아무것도 뜨지않음.
implements ActionListener, Runnable {
Button bt1, bt2, bt3, bt4;
TextField tf1, tf2, tf3; //connect, save, message 등
TextArea area; // 많이 적을 수 있는 곳.(darkgrary)
List list;//오른쪽 흰공간
Socket sock;
BufferedReader in;
PrintWriter out;
String listTitle = "*******대화자명단*******";
boolean flag = false;
String filterList[] = {"바보","개새끼","새끼","자바","java"};
public ChatClient2() {
super(450, 500); //나타나는 창의 가로세로 크기
setTitle("MyChat 2.0");
Panel p1 = new Panel();
p1.add(new Label("Host", Label.RIGHT)); //LEFT RIGHT차이 잘 모르겠다.
p1.add(tf1 = new TextField("127.0.0.1"));
p1.add(new Label("Port", Label.RIGHT));
p1.add(tf2 = new TextField("8003"));
bt1 = new Button("connect");
bt1.addActionListener(this);
p1.add(bt1);
add(BorderLayout.NORTH, p1);
// //////////////////////////////////////////////////////////////////////////////////////////
area = new TextArea("ChatClient 2.0");
area.setBackground(Color.DARK_GRAY);
area.setForeground(Color.PINK);
area.setEditable(false);
add(BorderLayout.CENTER, area);
// /////////////////////////////////////////////////////////////////////////////////////////
Panel p2 = new Panel();
p2.setLayout(new BorderLayout());
list = new List();
list.add(listTitle);
p2.add(BorderLayout.CENTER, list);
Panel p3 = new Panel();
p3.setLayout(new GridLayout(1, 2));
bt2 = new Button("Save");
bt2.addActionListener(this);
bt3 = new Button("Message");
bt3.addActionListener(this);
p3.add(bt2);
p3.add(bt3);
p2.add(BorderLayout.SOUTH, p3);
add(BorderLayout.EAST, p2);
// ///////////////////////////////////////////////////////////////////////////////////////////
Panel p4 = new Panel();
tf3 = new TextField("", 50);
tf3.addActionListener(this);
bt4 = new Button("send");
bt4.addActionListener(this);
p4.add(tf3);
p4.add(bt4);
add(BorderLayout.SOUTH, p4);
validate();
}
public void run() {
try {
String host = tf1.getText().trim(); //빈 공간없이 가져온다.
int port = Integer.parseInt(tf2.getText().trim()); //정수로 변환하여 빈틈없이 가져옴
connect(host,port); //host와 port를 연결. 밑에 메서드 있다.
area.append(in.readLine() + "\n");
while(true) {
String line = in.readLine();
if(line == null)
break;
else
routine(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}//--run
public void routine(String line) {
int idx = line.indexOf(ChatProtocol2.DM);
String cmd = line.substring(0, idx); //string 객체의 시작 인덱스로 위치부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다.
String data = line.substring(idx + 1);//위치 다음부터 끝까지
if(cmd.equals(ChatProtocol2.CHATLIST)){//String line = in.readLine(); readLine():파일의 한 줄을 가져와 문자열로 반환합니다.
// CHATLIST: 대화자명단
// data = aaa;bbb;홍길동;ddd;이렇게 데이터가 넘어올것이다. getId로 형식만들어놓음
list.removeAll();
list.add(listTitle); //**대화자명단*** 이 한 문장
StringTokenizer st = new StringTokenizer(data,";"); //StringTokenizer 아주 유용하다. 잘 사용해라
// StringTokenizer: 문자열을 우리가 지정한 구분자로 문자열을 쪼개주는 클래스입니다. 그렇게 쪼개어진 문자열을 우리는 토큰(token)이라고 부릅니다.
while(st.hasMoreTokens()) {
list.add(st.nextToken());
} //끝까지 돌다가 더 이상 없으면 false. while탈출.
}else if(cmd.equals(ChatProtocol2.CHAT)|| //cmd : line.substring(0, idx);
cmd.equals(ChatProtocol2.CHATALL)) {
area.append(data + "\n");
}else if(cmd.equals(ChatProtocol2.MESSAGE)) {
// data = bbb;밥먹자.. <-이런 형식을 데이터 넘어올것이다.
idx = data.indexOf(';'); //데이터를 쪼갠다.
cmd = data.substring(0,idx); //bbb
data = data.substring(idx+1);//밥먹자
new Message("FROM:",cmd,data);
}
}//--routine
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if(obj == bt1) { //bt1 = connect버튼
new Thread(this).start(); //run()호출 결과
bt1.setEnabled(false);
tf1.setEnabled(flag);
tf2.setEnabled(flag);
area.setText("");
}else if(obj == bt2) { //save버튼 :대화내용저장
try {
// FileWriter : 파일생성이 자동으로된다.
long file = System.currentTimeMillis();
FileWriter fw = new FileWriter("ch14/" +file+".txt");
fw.write(area.getText());
fw.flush();
fw.close();
area.setText("");//초기화
new MDialog(this, "Save", "대화내용을 저장하였습니다.");
} catch (Exception e2) {
e2.printStackTrace();
}
}else if(obj == bt3) { //message버튼, 누르면 따로 흰 창 생긴다.
int idx = list.getSelectedIndex();
if(idx ==-1 || idx==0) { //id 선택안하면 -1, 선택 고정되면 0
new MDialog(this,"경고","아이디를 선택하세요");
} else {
new Message("TO:"); //이거 밑에꺼와 다르면 오류생긴다.
}
}else if(obj == bt4 || obj == tf3) {
String str = tf3.getText().trim(); //맨 밑의 흰 창 값 가져오는 것.
if(str.length()==0) {
return;
}
if(filterMgr(str)) {
new MDialog(this,"경고","입력하신 글자는 금지어입니다.");//this :default가 비활성화라서
return;
}
// id입력 경우 또는 채팅
// 위에서 flag=false해놓음
if(!flag) {//id입력
// 서버로 id에 값을 보낸다.
sendMessage(ChatProtocol2.ID + ChatProtocol2.DM + str);
setTitle(getTitle() + "-" + str + "님 반갑습니다.");
area.setText("");
tf3.setText("");
tf3.requestFocus();
flag = true;//여기까지 단체 채팅
}else { //채팅
int idx = list.getSelectedIndex();
// System.out.println("idx : " + idx);
//INDEX :순서값에 대한 값. ITEM 들어있는 값 가져오기 둘이 다르다!
if(idx ==0 || idx ==-1) {//전체채팅
sendMessage(ChatProtocol2.CHATALL + ChatProtocol2.DM + str);
} else { //귓속말채팅(단체채팅 중 둘이서만 채팅하기 1:1채팅과는 다르다)
String id = list.getSelectedItem();
sendMessage(ChatProtocol2.CHAT+ChatProtocol2.DM + id +";"+str);
}
tf3.setText("");
tf3.requestFocus(); //대화자 id에 focus가 없을 때 콘솔에 -1나옴
}
}
}//--actionPerformed
public void connect(String host, int port) {
try {
sock = new Socket(host, port);
in = new BufferedReader(
new InputStreamReader(
sock.getInputStream()));
out = new PrintWriter(
sock.getOutputStream(),true/*auto flush*/);
} catch (Exception e) {
e.printStackTrace();
}
}//--connect
public void sendMessage(String msg) {
out.println(msg);
}
public boolean filterMgr(String msg){
boolean flag = false;//false이면 금지어 아님
//StringTokenizer쌤이 사용했음, contains 준영씨가 사용함.
for (int i = 0; i < filterList.length; i++) {
if(msg.contains(filterList[i])) {
flag = true;
// break; 이거말구 밑에꺼 해도 될듯.
return true;
}
}
// return flag;말구. 이렇게 해야 다음 문장이 금지어아니게 된다.
return false;
}
class Message extends Frame implements ActionListener {
Button send, close;
TextField name;
TextArea ta;
String mode;// to/from
String id;
public Message(String mode) {
setTitle("쪽지보내기");
this.mode = mode;
id = list.getSelectedItem();
layset("");
validate();
}
public Message(String mode, String id, String msg) {
setTitle("쪽지읽기");
this.mode = mode;
this.id = id;
layset(msg);
validate();
}
public void layset(String msg) {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
Panel p1 = new Panel();
p1.add(new Label(mode, Label.CENTER));
name = new TextField(id, 20);
p1.add(name);
add(BorderLayout.NORTH, p1);
ta = new TextArea("");
add(BorderLayout.CENTER, ta);
ta.setText(msg);
Panel p2 = new Panel();
if (mode.equals("TO:")) { //위에 "TO"와 동일해야
p2.add(send = new Button("send"));
send.addActionListener(this);
}
p2.add(close = new Button("close"));
close.addActionListener(this);
add(BorderLayout.SOUTH, p2);
setBounds(200, 200, 250, 250);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==send){
sendMessage(ChatProtocol2.MESSAGE+
ChatProtocol2.DM+id+";"+ ta.getText()); //send이벤트
}
setVisible(false); //창을 화면에 띄울 것인지 묻는다.
dispose();
}
}
class MDialog extends Dialog implements ActionListener{
// Dialog : 화면에 경고창같은 꺼 뜬다.
Button ok;
ChatClient2 ct2;
public MDialog(ChatClient2 ct2,String title, String msg) {
super(ct2, title, true);
this.ct2 = ct2;
//////////////////////////////////////////////////////////////////////////////////////////
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
/////////////////////////////////////////////////////////////////////////////////////////
setLayout(new GridLayout(2,1));
Label label = new Label(msg, Label.CENTER);
add(label);
add(ok = new Button("확인"));
ok.addActionListener(this);
layset();
setVisible(true);
validate();
}
public void layset() {
int x = ct2.getX();
int y = ct2.getY();
int w = ct2.getWidth();
int h = ct2.getHeight();
int w1 = 150;
int h1 = 100;
setBounds(x + w / 2 - w1 / 2,
y + h / 2 - h1 / 2, 200, 100);
}
public void actionPerformed(ActionEvent e) {
tf3.setText("");
dispose();
}
}
public static void main(String[] args) {
new ChatClient2();
}
}
package ch14;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
public class ChatServer3 {
ServerSocket server;
int port = 8004;
Vector<ClientThread3> vc;
ChatMgr3 mgr;
public ChatServer3() {
try {
server = new ServerSocket(port);
vc = new Vector<ClientThread3>();
mgr = new ChatMgr3();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error in Server");
System.exit(1);//비정상적인 종료
}
System.out.println("****************************");
System.out.println("Welcome Server 3.0...");
System.out.println("클라이언트의 접속을 기다리고 있습니다.");
System.out.println("****************************");
try {
while(true) {
Socket sock = server.accept();
ClientThread3 ct = new ClientThread3(sock);
ct.start();//쓰레드 스케줄러에 등록 -> run 메소드 호출
vc.addElement(ct);//ClientThread 객체를 벡터에 저장
}
} catch (Exception e) {
System.err.println("Error in sock");
e.printStackTrace();
}
}
//모든 접속된 Client에게 메세지 전달
public void sendAllMessage(String msg) {
for (int i = 0; i < vc.size(); i++) {
//Vector에 저장된 ClientThread를 순차적으로 자져옴
ClientThread3 ct = vc.get(i);
//ClientThread 가지고 있는 각각의 메세지 보내는 메소드 호출
ct.sendMessage(msg);
}
}
//접속이 끊어진 ClientThread는 벡터에서 제거
public void removeClient(ClientThread3 ct) {
vc.remove(ct);
}
//접속된 모든 id 리스트 ex)aaa;bbb;ccc;강호동;
public String getIds() {
String ids = "";
for (int i = 0; i < vc.size(); i++) {
ClientThread3 ct = vc.get(i);
ids+=ct.id+";";
}
return ids;
}
//지정한 ClientThread2 검색
public ClientThread3 findClient(String id) {
ClientThread3 ct = null;
for (int i = 0; i < vc.size(); i++) {
ct = vc.get(i);
if(id.equals(ct.id)) {
break;
}//--if
}//--for
return ct;
}
class ClientThread3 extends Thread{
Socket sock;
BufferedReader in;
PrintWriter out;
String id;
public ClientThread3(Socket sock) {
try {
this.sock = sock;
in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream(), true);
System.out.println(sock + " 접속됨...");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while(true) {
String line = in.readLine();
if(line==null)
break;
else
routine(line);
}
in.close();
out.close();
sock.close();
removeClient(this);
} catch (Exception e) {
removeClient(this);
System.err.println(sock + "[" + id +"] 끊어짐...");
}
}
public void routine(String line) {
int idx = line.indexOf(ChatProtocol3.DM);//;
String cmd = line.substring(0, idx);//CHATALL
String data = line.substring(idx+1);//[aaa]오늘은 월요일입니다.
if(cmd.equals(ChatProtocol3.ID)) {
//로그인 하면 여기로 온다. 성공하면 true t 보냄.그러면 채팅 프로그램으로 넘어감
// 로그인 아이디 패스워드 틀렸을 경우
// 이중접속
idx = data.indexOf(";");//aaa;1234
cmd = data.substring(0, idx);//CHATALL
data = data.substring(idx+1);
System.out.println(mgr.loginChk(cmd, data));
}else if(cmd.equals(ChatProtocol3.CHAT)) {
idx = data.indexOf(';');
cmd = data.substring(0, idx);//bbb
data = data.substring(idx+1);//data
ClientThread3 ct = findClient(cmd);
if(ct!=null) {//현재 접속자
ct.sendMessage(ChatProtocol3.CHAT+ChatProtocol3.DM+"["
+id+"(S)]" + data);//CHAT:[aaa(S)]밥먹자
sendMessage(ChatProtocol3.CHAT+ChatProtocol3.DM+"["
+id+"(S)]" + data);//CHAT:[aaa(S)]밥먹자
}else {//bbb가 접속이 안된 경우
sendMessage(ChatProtocol3.CHAT+ChatProtocol3.DM+"["+
cmd+"]님 접속자가 아닙니다.");
}
}else if(cmd.equals(ChatProtocol3.MESSAGE)) {
idx = data.indexOf(';');
cmd = data.substring(0, idx);//bbb
data = data.substring(idx+1);//data
ClientThread3 ct = findClient(cmd);
if(ct!=null) {//현재 접속자
ct.sendMessage(ChatProtocol3.MESSAGE+ChatProtocol3.DM+
id+";" + data);
}else {//bbb가 접속이 안된 경우
sendMessage(ChatProtocol3.CHAT+ChatProtocol3.DM+"["+
cmd+"]님 접속자가 아닙니다.");
}
}else if(cmd.equals(ChatProtocol3.CHATALL)) {
sendAllMessage(ChatProtocol3.CHATALL+ChatProtocol3.DM+"["+
id+"]"+data);
}
}
//Client에게 메세지 전달 메소드
public void sendMessage(String msg) {
out.println(msg);
}
}
public static void main(String[] args) {
new ChatServer3();
}
}
package ch14;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class ChatMgr3 {
private DBConnectionMgr pool;
public ChatMgr3() {
pool = DBConnectionMgr.getInstance();
}
// 로그인
public boolean loginChk(String id, String pwd) {
Connection con = null; //.sql에서 받아와야한다.ctrl space할 때
PreparedStatement pstmt = null; //u,d,s에서 필요
ResultSet rs = null; //select에서 필요
String sql = null;
boolean flag = false;
try {
con = pool.getConnection(); // Connection 빌려옴
sql = "select id from tblRegister where id = ? and pwd=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id); //첫번째 ?에 id ='aaa' 자바, sql에서 문자형은 각각 다르다.
pstmt.setString(2, pwd); //두번째 ?에 pwd ='1234'
rs = pstmt.executeQuery(); //실제 실행문
flag = rs.next(); //결과값이 있으면 true, 없으면 false->결과값 리턴
} catch (Exception e) {
e.printStackTrace();
} finally {
// con은 반납, pstmt, rs은 둘 다 close
pool.freeConnection(con, pstmt, rs);
}
return flag;
}
}
package ch14;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
class LoginAWT3 extends MFrame implements ActionListener {
TextField idTf, pwTf;
Label logo, idl, pwl, msgl;
Button logBtn;
Socket sock;
BufferedReader in;
PrintWriter out;
String id;
String host = "127.0.0.1";
int port = 8004;
String title = "MyChat 3.0";
String label[] = {"ID와 PWD를 입력하세요.",
"ID와 PWD를 확인하세요.",
"이중 접속입니다."};
public LoginAWT3() {
super(450, 400, new Color(100, 200, 100));
setLayout(null);
setTitle(title);
logo = new Label(title);
logo.setFont(new Font("Dialog", Font.BOLD, 50));
idl = new Label("ID");
pwl = new Label("PWD");
idTf = new TextField("aaa");
pwTf = new TextField("1234");
logBtn = new Button("로그인");
msgl = new Label(label[0]);
logo.setBounds(100, 60, 270, 100);
idl.setBounds(150, 200, 50, 20);
idTf.setBounds(200, 200, 100, 20);
pwl.setBounds(150, 230, 50, 20);
pwTf.setBounds(200, 230, 100, 20);
logBtn.setBounds(150, 260, 150, 40);
msgl.setBounds(150, 320, 150, 40);
logBtn.addActionListener(this);
add(logo);
add(idl);
add(idTf);
add(pwl);
add(pwTf);
add(logBtn);
add(msgl);
}
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if(obj == logBtn) {
connect();
id = idTf.getText().trim();
out.println(ChatProtocol3.ID + ChatProtocol3.DM + id + ";" + pwTf.getText().trim());
}
}
public void connect() {
try {
if(sock ==null) {
sock = new Socket(host, port);
in = new BufferedReader(
new InputStreamReader(
sock.getInputStream()));
out = new PrintWriter(
sock.getOutputStream(),true/*auto flush*/);
}
} catch (Exception e) {
e.printStackTrace();
}
}//--connect
public static void main(String[] args) {
new LoginAWT3();
}
}
package ch14;
/**
* Copyright(c) 2001 iSavvix Corporation (http://www.isavvix.com/)
*
* All rights reserved
*
* Permission to use, copy, modify and distribute this material for
* any purpose and without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies, and that the name of iSavvix Corporation not be used in
* advertising or publicity pertaining to this material without the
* specific, prior written permission of an authorized representative of
* iSavvix Corporation.
*
* ISAVVIX CORPORATION MAKES NO REPRESENTATIONS AND EXTENDS NO WARRANTIES,
* EXPRESS OR IMPLIED, WITH RESPECT TO THE SOFTWARE, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR ANY PARTICULAR PURPOSE, AND THE WARRANTY AGAINST
* INFRINGEMENT OF PATENTS OR OTHER INTELLECTUAL PROPERTY RIGHTS. THE
* SOFTWARE IS PROVIDED "AS IS", AND IN NO EVENT SHALL ISAVVIX CORPORATION OR
* ANY OF ITS AFFILIATES BE LIABLE FOR ANY DAMAGES, INCLUDING ANY
* LOST PROFITS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES RELATING
* TO THE SOFTWARE.
*
*/
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Vector;
/**
* Manages a java.sql.Connection pool.
*
* @author Anil Hemrajani
*/
public class DBConnectionMgr {
private Vector connections = new Vector(10);
private String _driver = "com.mysql.cj.jdbc.Driver",
_url = "jdbc:mysql://127.0.0.1:3306/myChat?useUnicode=true&serverTimezone=Asia/Seoul",
_user = "root",
_password = "1234";
private boolean _traceOn = false;
private boolean initialized = false;
private int _openConnections = 50;
private static DBConnectionMgr instance = null;
public DBConnectionMgr() {
}
/** Use this method to set the maximum number of open connections before
unused connections are closed.
*/
public static DBConnectionMgr getInstance() {
if (instance == null) {
synchronized (DBConnectionMgr.class) {
if (instance == null) {
instance = new DBConnectionMgr();
}
}
}
return instance;
}
public void setOpenConnectionCount(int count) {
_openConnections = count;
}
public void setEnableTrace(boolean enable) {
_traceOn = enable;
}
/** Returns a Vector of java.sql.Connection objects */
public Vector getConnectionList() {
return connections;
}
/** Opens specified "count" of connections and adds them to the existing pool */
public synchronized void setInitOpenConnections(int count)
throws SQLException {
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < count; i++) {
c = createConnection();
co = new ConnectionObject(c, false);
connections.addElement(co);
trace("ConnectionPoolManager: Adding new DB connection to pool (" + connections.size() + ")");
}
}
/** Returns a count of open connections */
public int getConnectionCount() {
return connections.size();
}
/** Returns an unused existing or new connection. */
public synchronized Connection getConnection()
throws Exception {
if (!initialized) {
Class c = Class.forName(_driver);
DriverManager.registerDriver((Driver) c.newInstance());
initialized = true;
}
Connection c = null;
ConnectionObject co = null;
boolean badConnection = false;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
// If connection is not in use, test to ensure it's still valid!
if (!co.inUse) {
try {
badConnection = co.connection.isClosed();
if (!badConnection)
badConnection = (co.connection.getWarnings() != null);
} catch (Exception e) {
badConnection = true;
e.printStackTrace();
}
// Connection is bad, remove from pool
if (badConnection) {
connections.removeElementAt(i);
trace("ConnectionPoolManager: Remove disconnected DB connection #" + i);
continue;
}
c = co.connection;
co.inUse = true;
trace("ConnectionPoolManager: Using existing DB connection #" + (i + 1));
break;
}
}
if (c == null) {
c = createConnection();
co = new ConnectionObject(c, true);
connections.addElement(co);
trace("ConnectionPoolManager: Creating new DB connection #" + connections.size());
}
return c;
}
/** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
public synchronized void freeConnection(Connection c) {
if (c == null)
return;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
if (c == co.connection) {
co.inUse = false;
break;
}
}
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
if ((i + 1) > _openConnections && !co.inUse)
removeConnection(co.connection);
}
}
public void freeConnection(Connection c, PreparedStatement p, ResultSet r) {
try {
if (r != null) r.close();
if (p != null) p.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, Statement s, ResultSet r) {
try {
if (r != null) r.close();
if (s != null) s.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, PreparedStatement p) {
try {
if (p != null) p.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, Statement s) {
try {
if (s != null) s.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
/** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
public synchronized void removeConnection(Connection c) {
if (c == null)
return;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
if (c == co.connection) {
try {
c.close();
connections.removeElementAt(i);
trace("Removed " + c.toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
private Connection createConnection()
throws SQLException {
Connection con = null;
try {
if (_user == null)
_user = "";
if (_password == null)
_password = "";
Properties props = new Properties();
props.put("user", _user);
props.put("password", _password);
con = DriverManager.getConnection(_url, props);
} catch (Throwable t) {
throw new SQLException(t.getMessage());
}
return con;
}
/** Closes all connections and clears out the connection pool */
public void releaseFreeConnections() {
trace("ConnectionPoolManager.releaseFreeConnections()");
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
if (!co.inUse)
removeConnection(co.connection);
}
}
/** Closes all connections and clears out the connection pool */
public void finalize() {
trace("ConnectionPoolManager.finalize()");
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
try {
co.connection.close();
} catch (Exception e) {
e.printStackTrace();
}
co = null;
}
connections.removeAllElements();
}
private void trace(String s) {
if (_traceOn)
System.err.println(s);
}
}
class ConnectionObject {
public java.sql.Connection connection = null;
public boolean inUse = false;
public ConnectionObject(Connection c, boolean useFlag) {
connection = c;
inUse = useFlag;
}
}
CREATE DATABASE myChat;
USE myChat;
CREATE TABLE tblRegister(
id VARCHAR(20) PRIMARY KEY,
pwd VARCHAR(20) NOT NULL,
NAME VARCHAR(20) NOT NULL,
regdate DATETIME DEFAULT NOW()
)
INSERT tblRegister VALUES ('aaa','1234','강호동',NOW());
INSERT tblRegister VALUES ('bbb','1234','오지혁',NOW());
INSERT tblRegister VALUES ('ccc','1234','강도장',NOW());
SELECT * FROM tblRegistermyChat