회원가입 - > 로그인 -> 메인화면(친구목록, 메세지목록)
친구목록 클릭 -> 메세시 작성
메세지목록 클릭 -> 받은 메세지 보기
받은 메세지와 파일, 회원가입 정보는 DB에 저장
package client;
import gui.JoinFrame;
import gui.LoginFrame;
import host.Host;
import java.net.Socket;
public class MainRun {
public static void main(String[] args) {
LoginFrame login = new LoginFrame();
}
}
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import vo.ChatVO;
import vo.MemberVO;
public class ChatDao {
private Connection jdbcInit() {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.12:1521:XE", "mini", "mini");
System.out.println("Connection 생성 여부 확인 : " + conn);
//getConnection 매개변수에 들어가야할 내용
//Oracle 접속주소, 계정 암호
} catch (ClassNotFoundException e) {
try {
conn.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
} catch (SQLException sqle) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sqle.printStackTrace();
}
return conn;
} // jdbcInit() 메소드 종료문
public int insertChat(ChatVO cv) {
PreparedStatement pstmt = null;
Connection conn = jdbcInit();
String sql = "INSERT INTO chat(num, sendId, receiveId, message, state, filelink, time) VALUES(SEQ_CHAT_NUM.nextval, ?, ?, ?, ?, ?, SYSDATE )";
int result_cnt=0;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, cv.getSendId());
pstmt.setString(2, cv.getReceiveId());
pstmt.setString(3, cv.getMessage());
pstmt.setInt(4, cv.getState());
pstmt.setString(5, cv.getFilelink());
result_cnt = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result_cnt;
}//insertChat() 종료
public List<ChatVO> getAllChat() {
Connection conn = null;
conn = jdbcInit();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT sendid, receiveid, message, state, filelink, time FROM chat";
List<ChatVO> list = new ArrayList<ChatVO>();
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
ChatVO cv = new ChatVO();
cv.setSendId(rs.getString(1));
cv.setReceiveId(rs.getString(2));
cv.setMessage(rs.getString(3));
cv.setState(rs.getInt(4));
cv.setFilelink(rs.getString(5));
cv.setTime(rs.getString(6));
list.add(cv);
}//while 종료지점
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//finally 종료 지점
return list;
}//
}
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import vo.ChatVO;
import vo.MemberVO;
public class MemberDao {
private Connection jdbcInit() {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.12:1521:XE", "mini", "mini");
System.out.println("Connection 생성 여부 확인 : " + conn);
//getConnection 매개변수에 들어가야할 내용
//Oracle 접속주소, 계정 암호
} catch (ClassNotFoundException e) {
e.printStackTrace();
try {
conn.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conn;
} // jdbcInit() 메소드 종료문
//Member정보 Insert하기
public int insertMember(MemberVO mv) {
PreparedStatement pstmt = null;
Connection conn = jdbcInit();
String sql = "INSERT INTO member(id, pw, name, email, nickname, profile) VALUES(?, ?, ?, ?, ?, ?)";
int result_cnt=0;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, mv.getId());
pstmt.setString(2, mv.getPw());
pstmt.setString(3, mv.getName());
pstmt.setString(4, mv.getEmail());
pstmt.setString(5, mv.getNickname());
pstmt.setString(6, mv.getProfile());
result_cnt = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//finally 종료
return result_cnt;
}//insertMember() 종료
public List<MemberVO> getAllMember() {
Connection conn = null;
conn = jdbcInit();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT id, pw, name, email, nickname, profile FROM member";
List<MemberVO> list = new ArrayList<MemberVO>();
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
MemberVO mv = new MemberVO();
mv.setId(rs.getString(1));
mv.setPw(rs.getString(2));
mv.setName(rs.getString(3));
mv.setEmail(rs.getString(4));
mv.setNickname(rs.getString(5));
mv.setProfile(rs.getString(6));
list.add(mv);
}//while 종료지점
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//finally 종료 지점
return list;
}//getAllMember() 종료
public String getLoginInfo(String id, String pw) {
Connection conn = null;
conn = jdbcInit();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT id FROM member WHERE id = ? and pw = ?";
String result_id = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pw);
rs = pstmt.executeQuery();
while(rs.next()) {
result_id = rs.getString(1);
}//if 종료지점
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//finally 종료지점
return result_id;
}//getLoginInfo() 종료 지점
public int idCheck(String id) {
Connection conn = null;
conn = jdbcInit();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT COUNT(*) FROM member WHERE id = ?";
MemberVO mv = new MemberVO();
int result_idchk = 0;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
while(rs.next()) {
result_idchk = rs.getInt(1);
}//if종료 지점
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//finally 종료 지점
return result_idchk;
}//idCheck() 종료 지점
public List<MemberVO> getMemberList() {
Connection conn = null;
conn = jdbcInit();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT nickname FROM member";
List<MemberVO> list = new ArrayList<MemberVO>();
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
MemberVO mv = new MemberVO();
mv.setNickname(rs.getString(1));
list.add(mv);
}//while 종료 지점
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//finally 종료 지점
return list;
}//getMemberList() 종료 지점
}
#### gui
package gui;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import dao.MemberDao;
import host.Host;
import vo.ClientVO;
import vo.MemberVO;
public class JoinFrame extends JFrame {
ObjectOutputStream oos = null;
String code;
boolean idCheckFlag;
private JPanel contentPane;
private JLabel lblJoin;
private JButton joinCompleteBtn;
private JButton idCheck;
private JTextField tfUserid;
private JPasswordField tfPassword;
private JPasswordField tfPassword2;
private JTextField tfName;
private JTextField tfEmail;
private JTextField tfNickName;
private JTextField tfProfile;
// Socket socket;
// public void setSocket(Socket socket) {
// this.socket = socket;
// }
/**
* Create the frame.
*/
public JoinFrame(ClientVO cvo) {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(550, 590);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblJoin = new JLabel("회원가입");
Font f1 = new Font("돋움", Font.BOLD, 20); //궁서 바탕 돋움
lblJoin.setFont(f1);
lblJoin.setBounds(200, 41, 101, 20);
contentPane.add(lblJoin);
JLabel lblId = new JLabel("ID");
lblId.setBounds(69, 113, 69, 20);
contentPane.add(lblId);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(69, 163, 69, 20);
contentPane.add(lblPassword);
JLabel lblPassword2 = new JLabel("Password 확인");
lblPassword2.setBounds(69, 210, 100, 20);
contentPane.add(lblPassword2);
JLabel lblName = new JLabel("Name");
lblName.setBounds(69, 257, 69, 20);
contentPane.add(lblName);
JLabel lblEmail = new JLabel("E-mail");
lblEmail.setBounds(69, 304, 69, 20);
contentPane.add(lblEmail);
JLabel lblNickname = new JLabel("NickName");
lblNickname.setBounds(69, 351, 69, 20);
contentPane.add(lblNickname);
JLabel lblProfile = new JLabel("Profile");
lblProfile.setBounds(69, 398, 69, 20);
contentPane.add(lblProfile);
tfUserid = new JTextField();
tfUserid.setColumns(10);
tfUserid.setBounds(190, 106, 186, 35);
contentPane.add(tfUserid);
tfPassword = new JPasswordField();
tfPassword.setColumns(10);
tfPassword.setBounds(190, 156, 186, 35);
contentPane.add(tfPassword);
tfPassword2 = new JPasswordField();
tfPassword2.setColumns(10);
tfPassword2.setBounds(190, 203, 186, 35);
contentPane.add(tfPassword2);
tfName = new JTextField();
tfName.setColumns(10);
tfName.setBounds(190, 250, 186, 35);
contentPane.add(tfName);
tfEmail = new JTextField();
tfEmail.setColumns(10);
tfEmail.setBounds(190, 297, 186, 35);
contentPane.add(tfEmail);
tfNickName = new JTextField();
tfNickName.setColumns(10);
tfNickName.setBounds(190, 344, 186, 35);
contentPane.add(tfNickName);
tfProfile = new JTextField();
tfProfile.setColumns(10);
tfProfile.setBounds(190, 391, 186, 35);
contentPane.add(tfProfile);
joinCompleteBtn = new JButton("회원가입완료");
joinCompleteBtn.setBounds(206, 463, 139, 29);
contentPane.add(joinCompleteBtn);
idCheck = new JButton("ID 중복체크");
idCheck.setBounds(380, 110, 100, 29);
contentPane.add(idCheck);
setVisible(true);
System.out.println("회원가입 창");
//Id 중복 체크 액션
idCheck.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = tfUserid.getText();
MemberVO mvo = new MemberVO();
mvo.setCode(3);
mvo.setId(username);
try { //ID 중복 체크 ID 데이터 서버로 보내기
cvo.getOos().writeObject(mvo);
cvo.getOos().flush();
System.out.println("ID체크값 보냄");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
System.out.println("클라이언트 read");
code = cvo.getOis().readUTF();
System.out.println("code : "+code);
if(code.equals("S")){
JOptionPane.showMessageDialog(null, "사용가능한 ID 입니다");
idCheckFlag = true;
}else if(code.equals("F")){
JOptionPane.showMessageDialog(null, "이미 사용중인 ID 입니다.");
idCheckFlag = false;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
//회원가입완료 액션
joinCompleteBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = tfUserid.getText();
String password = tfPassword.getText();
String password2 = tfPassword2.getText();
String name = tfName.getText();
String email = tfEmail.getText();
String nickname = tfNickName.getText();
String profile = tfProfile.getText();
if(username.equals("")) {
JOptionPane.showMessageDialog(null, "항목이 비어있습니다.");
}else if(password.equals("")){
JOptionPane.showMessageDialog(null, "항목이 비어있습니다.");
}else if(password2.equals("")){
JOptionPane.showMessageDialog(null, "항목이 비어있습니다.");
}else if(name.equals("")){
JOptionPane.showMessageDialog(null, "항목이 비어있습니다.");
}else if(email.equals("")){
JOptionPane.showMessageDialog(null, "항목이 비어있습니다.");
}else if(nickname.equals("")){
JOptionPane.showMessageDialog(null, "항목이 비어있습니다.");
}
if(password.equals(password2) && idCheckFlag){ // 패스워드 맞을 경우 서버로 데이터 보냄
try {
MemberVO mvo = new MemberVO();
mvo.setCode(1);
mvo.setId(username);
mvo.setPw(password);
mvo.setName(name);
mvo.setEmail(email);
mvo.setNickname(nickname);
mvo.setProfile(profile);
System.out.println(mvo.getCode());
cvo.getOos().writeObject(mvo);
cvo.getOos().flush();
code = cvo.getOis().readUTF();
System.out.println(code);
if(code.equals("S")){
JOptionPane.showMessageDialog(null, "회원가입이 완료 되었습니다.");
dispose();
}else if(code.equals("F")){
JOptionPane.showMessageDialog(null, "회원가입에 문제가 생겼습니다.");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}else if(!password.equals(password2)) { // 패스워드 다를 경우 알림창 띄우고 다시 입력 알림 보여줌
JOptionPane.showMessageDialog(null, "비밀 번호가 다릅니다 확인해주세요");
} else {
JOptionPane.showMessageDialog(null, "ID 체크를 해주세요");
}
}
});
}
}
package gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import host.Host;
import vo.ClientVO;
import vo.MemberVO;
public class LoginFrame extends JFrame {
MemberVO mvo = new MemberVO();
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
DataInputStream dis = null;
DataOutputStream dos = null;
Host host = new Host(); // 생성자 초기화
Socket socket = host.socket(); //Host 소켓을 로그인으로 불러옴
private JPanel contentPane;
private JTextField tfUsername;
private JPasswordField tfPassword;
private JButton loginBtn, joinBtn;
/**
* Create the frame.
*/
public LoginFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblLogin = new JLabel("username");
lblLogin.setBounds(41, 52, 69, 35);
contentPane.add(lblLogin);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(41, 103, 69, 35);
contentPane.add(lblPassword);
tfUsername = new JTextField();
tfUsername.setBounds(157, 52, 176, 35);
contentPane.add(tfUsername);
tfUsername.setColumns(10);
joinBtn = new JButton("회원가입");
joinBtn.setBounds(229, 154, 104, 29);
contentPane.add(joinBtn);
loginBtn = new JButton("로그인");
loginBtn.setBounds(108, 154, 106, 29);
contentPane.add(loginBtn);
tfPassword = new JPasswordField("");
tfPassword.setColumns(10);
tfPassword.setBounds(157, 103, 176, 35);
contentPane.add(tfPassword);
ClientVO cvo = new ClientVO(); //클라이언트 VO 선언
try {
cvo.setSocket(socket);
// cvo.setDis(new DataInputStream(socket.getInputStream()));
// cvo.setDos(new DataOutputStream(socket.getOutputStream()));
cvo.setOos(new ObjectOutputStream(socket.getOutputStream()));
cvo.setOis(new ObjectInputStream(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("로그인창");
setVisible(true);
//회원가입 액션
joinBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JoinFrame frame = new JoinFrame(cvo);
// frame.setSocket(socket);
}
});
//로그인 액션
loginBtn.addActionListener(new ActionListener() { // 로그인 버튼 눌렀을 때 서버로 ID, PW 보내기
// ObjectOutputStream oos = null;
@Override
public void actionPerformed(ActionEvent e) {
String username = tfUsername.getText();
String password = tfPassword.getText();
MemberVO mvo = new MemberVO();
mvo.setCode(2);
mvo.setId(username);
mvo.setPw(password);
try {
cvo.getOos().writeObject(mvo);
cvo.getOos().flush();
} catch (IOException ex) {
ex.printStackTrace();
} // 서버로 정보 보내기 끝
try {
String code = cvo.getOis().readUTF();
System.out.println(code);
if(code.equals("S")){
JOptionPane.showMessageDialog(null, "로그인 되었습니다.");
MainFrame mf = new MainFrame(cvo, username);
dispose();
}else if(code.equals("F")){
JOptionPane.showMessageDialog(null, "로그인에 실패하였습니다.");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
package gui;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import vo.ClientVO;
import vo.MemberVO;
public class MainFrame extends JFrame{
private JPanel mainPanel = new JPanel(); // 전체 패널
private JLabel mainLable = new JLabel("친구 목록"); // 친구 목록 - 텍스트
private JPanel frPanel = new JPanel();
// private
private JLabel idLable = new JLabel(); // id 님 환영합니다 - 텍스트
private JButton logoutBtn = new JButton(); // 로그아웃 버튼
private JButton msgListBtn = new JButton("메시지 목록"); // 메시지 목록
private JButton refreshFrBtn = new JButton("친구목록 새로고침");
private JButton refreshAccBtn = new JButton("접속자 새로고침");
private Map<JButton, JLabel> accList = new HashMap<JButton, JLabel>();
private ClientVO cvo;
public MainFrame(ClientVO cvo, String id) {
this.cvo = cvo;
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 300, 420);
mainPanel.setLayout(null);
mainLable.setBounds(100, 21, 88, 26);
mainLable.setFont(new Font("굴림", Font.BOLD, 18));
mainPanel.add(mainLable);
frPanel.setLayout(new GridLayout(0,2,5,5));
friendList(cvo, id);
JScrollPane frScrollPane = new JScrollPane(frPanel);
frScrollPane.setBounds(24, 57, 245, 239);
mainPanel.add(frScrollPane);
msgListBtn.setBounds(88, 306, 110, 23);
mainPanel.add(msgListBtn);
refreshFrBtn.setBounds(10, 340, 135, 30);
mainPanel.add(refreshFrBtn);
refreshAccBtn.setBounds(145, 340, 135, 30);
mainPanel.add(refreshAccBtn);
this.setContentPane(mainPanel);
this.setTitle("메인화면"); //프레임의 제목
this.setVisible(true); //프레임 활성화
msgListBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// accessUpdate("a2");
// accessUpdate("a6");
}
});
refreshFrBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MemberVO vo = new MemberVO();
vo.setCode(4);
try {
cvo.getOos().writeObject(vo);
friendList(cvo, id);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
refreshAccBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MemberVO vo = new MemberVO();
vo.setCode(5);
try {
cvo.getOos().writeObject(vo);
friendList(cvo, id);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
public void friendList(ClientVO cvo, String id) { //List<MemberVO> mlist
try {
frPanel.removeAll();
List<MemberVO> list = (List<MemberVO>)cvo.getOis().readObject();
for(MemberVO mvo : list) {
if(mvo.getId().equals(id)) {
continue;
}
JButton nicknameBtn = new JButton(mvo.getNickname());
JLabel loginState = new JLabel();
loginState.setHorizontalAlignment(JLabel.CENTER);
//초기 미접속
loginState.setText("OFF");
// 배경색 적용
loginState.setOpaque(true);
loginState.setBackground(Color.red);
// accList.put(nicknameBtn, loginState);
frPanel.add(nicknameBtn);
frPanel.add(loginState);
nicknameBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MessageSendFrame msf = new MessageSendFrame(cvo, id, mvo.getId());
}
});
}
frPanel.validate();
frPanel.repaint();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void accessUpdate(List<String> idList) {
// for(String id : idList) {
// loginState.setOpaque(true);
//
// if(nickNameBtn.getText().equals(nickname)) { //접속
// loginState.setText("ON");
// // 배경색 적용
// loginState.setBackground(Color.green);
// }
// }
}
// public static void main(String[] args) {
// new MainFrame();
// }
}
package gui;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import vo.ChatVO;
import vo.ClientVO;
public class MessageListFrame extends JFrame {
private JTabbedPane tabPanel = new JTabbedPane();
private JPanel allMsgPanel = new JPanel();
private JPanel readMsgPanel = new JPanel();
private JPanel noReadMsgPanel = new JPanel();
private DefaultTableModel allModel;
private DefaultTableModel readModel;
private DefaultTableModel noReadModel;
// private JScrollPane scrollPane = new JScrollPane();
public MessageListFrame(ClientVO cvo) {
this.setDefaultCloseOperation(EXIT_ON_CLOSE); //정상종료 되게
this.setBounds(100, 100, 500, 500); //창 위치 및 크기
this.setLayout(new GridLayout(1,1));
//헤더 값
String header[] = {"보낸사람","받는사람","내용","전송시간","읽음","파일"};
//샘플 데이터
// String contents1[][] = {
// {"sender","receiver","안녕","22/01/20 11:00:00","Y", "N"},
// {"sender","receiver","안녕","22/01/20 11:00:00","N", "N"},
// };
//
// String contents2[][] = {
// {"sender1","receiver1","안녕1","22/01/20 11:00:00","Y", "N"},
// {"sender","receiver","안녕","22/01/20 11:00:00","N", "N"},
// };
//
// String contents3[][] = {
// {"sender2","receiver2","안녕2","22/01/20 11:00:00","Y", "N"},
// {"sender","receiver","안녕","22/01/20 11:00:00","N", "N"},
// };
//전체 메시지 탭의 테이블
allModel = new DefaultTableModel(header,0);
JTable allTable = new JTable(allModel);
allTable.getColumnModel().getColumn(0).setPreferredWidth(25);
allTable.getColumnModel().getColumn(1).setPreferredWidth(25);
allTable.getColumnModel().getColumn(2).setPreferredWidth(50);
allTable.getColumnModel().getColumn(4).setPreferredWidth(10);
allTable.getColumnModel().getColumn(5).setPreferredWidth(10);
JScrollPane allScrollPane = new JScrollPane(allTable);
//읽은 메시지 탭의 테이블
readModel = new DefaultTableModel(header,0);
JTable readTable = new JTable(readModel);
readTable.getColumnModel().getColumn(0).setPreferredWidth(25);
readTable.getColumnModel().getColumn(1).setPreferredWidth(25);
readTable.getColumnModel().getColumn(2).setPreferredWidth(50);
readTable.getColumnModel().getColumn(4).setPreferredWidth(10);
readTable.getColumnModel().getColumn(5).setPreferredWidth(10);
JScrollPane readScrollPane = new JScrollPane(readTable);
//안 읽은 메시지 탭의 테이블
noReadModel = new DefaultTableModel(header, 0);
JTable noReadTable = new JTable(noReadModel);
noReadTable.getColumnModel().getColumn(0).setPreferredWidth(25);
noReadTable.getColumnModel().getColumn(1).setPreferredWidth(25);
noReadTable.getColumnModel().getColumn(2).setPreferredWidth(50);
noReadTable.getColumnModel().getColumn(4).setPreferredWidth(10);
noReadTable.getColumnModel().getColumn(5).setPreferredWidth(10);
JScrollPane noReadScrollPane = new JScrollPane(noReadTable);
allMsgPanel.add(allScrollPane);
readMsgPanel.add(readScrollPane);
noReadMsgPanel.add(noReadScrollPane);
tabPanel.addTab("전체 메시지", allMsgPanel);
tabPanel.addTab("읽은 메시지", readMsgPanel);
tabPanel.addTab("안읽은 메시지", noReadMsgPanel);
this.setContentPane(tabPanel);
this.setTitle("메인화면"); //프레임의 제목
this.setVisible(true); //프레임 활성화
ChatVO chatVO = new ChatVO();
chatVO.setCode(1);
try {
cvo.getOos().writeObject(chatVO);
List<ChatVO> list = (List<ChatVO>) cvo.getOis().readObject();
addRow(list);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//탭 클릭시 동작 이벤트
tabPanel.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
//tab 클릭시 동작
if (tabPanel == e.getSource()) {
if (tabPanel.getSelectedIndex() == 0) {//전체
}else if (tabPanel.getSelectedIndex() == 1) { //읽음
}else {//안읽음
}
}
}
});
}
//테이블에 전체 데이터 추가
public void addRow(List<ChatVO> clist) {
String[] chatCol = new String[5];
for (ChatVO cvo : clist) {
chatCol[0] = cvo.getSendId();
chatCol[1] = cvo.getReceiveId();
chatCol[2] = cvo.getMessage();
chatCol[3] = cvo.getTime();
chatCol[4] = String.valueOf(cvo.getState());
chatCol[5] = cvo.getFilelink();
allModel.addRow(chatCol);
}
}
// public static void main(String[] args) {
// Socket socket=null;
//// DataOutputStream dos=null;
//
// try {
// socket=new Socket("localhost",7777);
// System.out.println("서버 데이터 요청");
// OutputStream os=socket.getOutputStream();
// oos=new ObjectOutputStream(os);
//// oj=new ObjectInputStream(socket.getInputStream());
// int data=1;//1은 전체,2는 읽음, 3은 안읽음 일단 이렇게 생각
// oos.writeObject(data);
// oos.flush();
// try {
//
// mlf.addRow((ArrayList<ChatVO>) oj.readObject());
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// } catch (UnknownHostException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }finally {
// try {
// socket.close();
// } catch (Exception e2) {
// // TODO: handle exception
// }
// }
//
// }
}
package gui;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import vo.ChatVO;
import vo.ClientVO;
public class MessageReceiveFrame extends JFrame {
private JPanel mainPanel = new JPanel(); //전체 패널
private JPanel imgPanel = new JPanel(); //이미지가 들어갈 패널
private JPanel bottomPanel = new JPanel(); //파일, 보내기 버튼이 들어간 패널
private JTextArea textArea = new JTextArea(); //메시지 적는 공간
private JFileChooser file = new JFileChooser();
private JButton downBtn = new JButton(); //파일 버튼
private JTextField textField = new JTextField(); //파일 경로 적히는 곳
private JButton sendBtn = new JButton(); //보내기 버튼
private ImageIcon img = null;
public MessageReceiveFrame(ChatVO vo, ClientVO cvo) {
// 메세지 전송시 활용 변수
String sendId = vo.getSendId();
String receiveId = vo.getReceiveId();
/* UI */
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); //정상종료 되게
this.setBounds(100, 100, 500, 300); //창 위치 및 크기
// this.setResizable(false); //창크기 고정
this.setLayout(new FlowLayout());
mainPanel.setLayout(null);
mainPanel.setBounds(0,0,500,350);
bottomPanel.setLayout(null);
bottomPanel.setBounds(0,150,500,150);
downBtn.setText("다운로드");
downBtn.setBounds(30,40,100,30);
textField.setBounds(130, 40, 150, 30);
textField.setFocusable(false);
sendBtn.setText("답장");
sendBtn.setBounds(350,40,100,30);
bottomPanel.add(downBtn);
bottomPanel.add(textField);
bottomPanel.add(sendBtn);
profilePaint("춘삼이.jpg"); //프로필 사진 넣는곳 test
Image profile=img.getImage();
Image scaledImg = profile = profile.getScaledInstance(150, 150, Image.SCALE_SMOOTH);
JLabel imgLabel = new JLabel(new ImageIcon(scaledImg));
imgPanel.add(imgLabel);
imgPanel.setBounds(10,10, 150, 150);
mainPanel.add(imgPanel);
textArea.setBounds(170, 10, 300, 150);
mainPanel.add(textArea);
mainPanel.add(bottomPanel);
this.setContentPane(mainPanel);
String id = "보낸사람 ID";
this.setTitle(id); //프레임의 제목
this.setVisible(true); //프레임 활성화
/* UI end */
FileOutputStream fos = null;
DataInputStream dis = null;
ObjectInputStream ois = null;
try {
String ori_file = textField.getText();
ois = cvo.getOis(); // 메세지 스트림
dis = cvo.getDis(); // 파일 스트림
fos = new FileOutputStream(ori_file);
//메세지 내용
// vo.getMessage();
// vo.getSendName();
// vo.getReceiveName();
// vo.getMessage();
// vo.getState();
// vo.getFilelink();
// vo.getTime();
//ChatVO voo = (ChatVO)ois.readObject();
// 파일 받기
// while(true) {
// int data = dis.read();
// if (data == -1) {
// break;}
// fos.write(data);
// }
// dis.close();
// }
}catch (Exception e2) {
e2.printStackTrace();
}
//
//답장 버튼 클릭
sendBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MessageSendFrame mf = new MessageSendFrame(cvo.getSocket());
}
});
//다운로드 버튼 클릭
downBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFrame window = new JFrame();
JFileChooser fileChooser = new JFileChooser();
int ssd = fileChooser.showSaveDialog(window);
if(ssd == JFileChooser.APPROVE_OPTION) {//
//선택한 파일의 경로 반환
File selectedFile = fileChooser.getSelectedFile();
//경로 출력
System.out.println(selectedFile);
}
}
});
}
//메시지 창 프로필 그리기
public void profilePaint(String path) {
img = new ImageIcon(this.getClass().getResource(path)); //프로필 이미지
}
public static void main(String[] args) {
}
}
package gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import vo.ChatVO;
import vo.ClientVO;
public class MessageSendFrame extends JFrame {
private JPanel mainPanel = new JPanel(); //전체 패널
private JPanel imgPanel = new JPanel(); //이미지가 들어갈 패널
private JPanel bottomPanel = new JPanel(); //파일, 보내기 버튼이 들어간 패널
private JTextArea textArea = new JTextArea(); //메시지 적는 공간
private JFileChooser file = new JFileChooser();
private JButton fileBtn = new JButton(); //파일 버튼
private JTextField textField = new JTextField(); //파일 경로 적히는 곳
private JButton sendBtn = new JButton(); //보내기 버튼
private ImageIcon img = null;
public MessageSendFrame(ClientVO cvo, String id, String receiveId) {
this.setDefaultCloseOperation(EXIT_ON_CLOSE); //정상종료 되게
this.setBounds(100, 100, 500, 300); //창 위치 및 크기
// this.setResizable(false); //창크기 고정
this.setLayout(new FlowLayout());
mainPanel.setLayout(null);
mainPanel.setBounds(0,0,500,350);
bottomPanel.setLayout(null);
bottomPanel.setBounds(0,150,500,150);
fileBtn.setText("파일선택");
fileBtn.setBounds(30,40,100,30);
textField.setBounds(130, 40, 150, 30);
textField.setFocusable(false);
sendBtn.setText("보내기");
sendBtn.setBounds(350,40,100,30);
bottomPanel.add(fileBtn);
bottomPanel.add(textField);
bottomPanel.add(sendBtn);
profilePaint("춘삼이.jpg"); //프로필 사진 넣는곳 test
Image profile=img.getImage();
Image scaledImg = profile = profile.getScaledInstance(150, 150, Image.SCALE_SMOOTH);
JLabel imgLabel = new JLabel(new ImageIcon(scaledImg));
imgPanel.add(imgLabel);
imgPanel.setBounds(10,10, 150, 150);
mainPanel.add(imgPanel);
textArea.setBounds(170, 10, 300, 150);
mainPanel.add(textArea);
mainPanel.add(bottomPanel);
this.setContentPane(mainPanel);
this.setTitle(id); //프레임의 제목
this.setVisible(true); //프레임 활성화
//보내기 버튼 클릭
sendBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// FileInputStream fis = null;
try {
ChatVO vo = new ChatVO();
String ori_file = textField.getText();
String message = textArea.getText();
// cvo.setDos(new DataOutputStream(socket.getOutputStream())); // 파일 전송 스트림
// cvo.setOos(new ObjectOutputStream(socket.getOutputStream())); // 메세지 내용 전송 스트림
//현재시간
// SimpleDateFormat format = new SimpleDateFormat ("yyyy년 MM월dd일 HH시mm분ss초");
// Date time = new Date();
// String time1 = format.format(time);
// oos = null; // 메세지 내용 전송 스트림
// dos = null; // 파일 전송 스트림
// fis = new FileInputStream(ori_file);
// 메세지 내용 전송
vo.setSendId(id);
vo.setReceiveId(receiveId);
vo.setMessage(message);
vo.setState(1);
vo.setFilelink(ori_file);
cvo.getOos().writeObject(vo);
cvo.getOos().flush();
// oos.writeObject(vo);
// oos.flush();
// 파일 전송
// while(true) {
//
// int data = fis.read();
// if (data == -1) {
// break;
//
// }
// cvo.getDos().write(data);
// }
dispose();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
});
//파일 버튼 클릭
fileBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int ret = file.showOpenDialog(null);
if(ret!= JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "파일을 선택하지 않았습니다.", "경고", JOptionPane.WARNING_MESSAGE);
return;
}
String filePath = file.getSelectedFile().getName();
textField.setText(filePath);
}
});
}
//메시지 창 프로필 그리기
public void profilePaint(String path) {
img = new ImageIcon(this.getClass().getResource(path)); //프로필 이미지
}
}
package host;
import java.io.IOException;
import java.net.Socket;
public class Host {
Socket socket = null;
public Socket socket(){
try {
socket = new Socket("localhost",7777);
System.out.println("server connection");
} catch (IOException e) {
e.printStackTrace();
}
return socket;
}
}
package server;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import vo.MemberVO;
import vo.ServerSocketVO;
public class Server {
// public static Map<String, Socket> list = new HashMap<String, Socket>();
public static List<ServerSocketVO> list = new ArrayList<ServerSocketVO>();
public static void main(String[] args) {
//서버 소켓 선언
ServerSocket serverSocket = null;
Socket socket = null;
//서버 소켓 생성
try {
serverSocket = new ServerSocket(7777);
while(true) {
//서버소켓 대기
System.out.println("서버 대기중...");
socket = serverSocket.accept();
System.out.println("서버 접속 완료");
//serverEcho 쓰레드 실행
Thread echoThread = new Thread(new ServerEcho(socket));
echoThread.start();
}//while 종료 지점
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//finally 종료 지점
}//main 메소드 종료 지점
}
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import dao.ChatDao;
import dao.MemberDao;
import vo.ChatVO;
import vo.MemberVO;
import vo.ServerSocketVO;
public class ServerEcho implements Runnable {
private Socket socket;
public ServerEcho(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
ObjectInputStream ois = null;
// DataOutputStream dos = null;
ObjectOutputStream oos = null;
// DataInputStream dis = null;
// FileOutputStream fos = null;
ServerSocketVO sv = null;
try {
ois = new ObjectInputStream(socket.getInputStream());
oos = new ObjectOutputStream(socket.getOutputStream());
MemberDao md = new MemberDao();
String result_2 = null;
while (true) {
System.out.println("read 시작");
Object obj = ois.readObject();
if (obj instanceof MemberVO) {
MemberVO mv = (MemberVO) obj;
// 회원가입 정보 받기
if (mv.getCode() == 1) {
System.out.println("회원가입");
// DB에 INSERT
int result_1 = md.insertMember(mv);
// 결과 통지(S/F)
if (result_1 == 1) {
oos.writeUTF("S");
oos.flush();
} else {
oos.writeUTF("F");
oos.flush();
}
// 로그인 정보 받고 신호뿌리기
} else if (mv.getCode() == 2) {
System.out.println("로그인");
result_2 = md.getLoginInfo(mv.getId(), mv.getPw());
if (result_2 != null) {
oos.writeUTF("S");
oos.writeObject(md.getAllMember()); //친구목록 전달
oos.flush();
// for (ServerSocketVO ssv : Server.list) {
// ssv.getOos().writeUTF("ON");
//
// }
sv = new ServerSocketVO();
sv.setSocket(socket);
sv.setOos(oos);
sv.setId(mv.getId());
Server.list.add(sv);
} else {
oos.writeUTF("F");
oos.flush();
}
// id중복체크
} else if (mv.getCode() == 3) {
System.out.println("id 중복체크");
int result_3 = md.idCheck(mv.getId());
if (result_3 == 0) {
System.out.println("ss");
oos.writeUTF("S");
oos.flush();
} else {
System.out.println("ff");
oos.writeUTF("F");
oos.flush();
}
} else if (mv.getCode() == 4) { //친구목록 새로고침
//친구목록
System.out.println("친구목록 새로고침");
List<MemberVO> list = md.getAllMember();
oos.writeObject(list);
oos.flush();
} else if (mv.getCode() == 5) { //접속자 새로고침
List<String> idList = new ArrayList<String>();
//접속 목록
for(ServerSocketVO ssvo : Server.list) {
idList.add(ssvo.getId());
}
oos.writeObject(idList);
oos.flush();
}
// 메시지 받기
} else if (obj instanceof ChatVO) {
ChatVO cv = (ChatVO) obj;
ChatDao cd = new ChatDao();
cd.insertChat(cv);
// String receiveId = cv.getReceiveId();
for (ServerSocketVO ssv : Server.list) {
if (ssv.getId().equals("bonse")) {
ssv.getOos().writeObject(cv);
ssv.getOos().flush();
break;
// 파일이 있을 경우 DataInputStream
// dis = new DataInputStream(socket.getInputStream());
} // if 종료 지점
} // for 종료 지점
} else if (obj instanceof ChatVO) {
ChatVO cv = (ChatVO) obj;
ChatDao cd = new ChatDao();
// 메세지 전체
if (cv.getCode() == 1) {
oos.writeObject(cd.getAllChat());
System.out.println("데이터 전송");
}
}
} // while종료 지점
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Server.list.remove(sv);
}
}
}