728x90
반응형
package p11_network;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
//1. 입력후 글자 지워짐
//2. 외부메세지를 textArea 에 보이게하기
//3. 스롤내려가게 만들기
//4. 메세지 공백 안보내지게
public class Ex01TcpIpMultiChatClient extends JFrame {
public static void main(String[] args) {
new Ex01TcpIpMultiChatClient();
}
private JTextArea ta;
private JScrollPane scp;
private JTextField tf;
private String nickname;
private DataOutputStream out;
public Ex01TcpIpMultiChatClient() throws HeadlessException {
init();
arrange();
inflate();
}
private void init() {
nickname = JOptionPane.showInputDialog("Input Nickname");
//10.100.204.26
String ip = JOptionPane.showInputDialog("Server IP", "10.100.204.26");
ta = new JTextArea();
ta.setEditable(false); //텍스트 수정 가능 여부
scp = new JScrollPane(ta);
tf = new JTextField();
//폰트 관련
ta.setFont(new Font("맑은 고딕", Font.PLAIN, 20));
tf.setFont(new Font("맑은 고딕", Font.PLAIN, 20));
//소켓 생성 , 입출력은 try catch 문이 따라옴
try {
Socket socket = new Socket(ip,7777);
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(nickname);
new Thread(new Reciver(socket)).start(); //implements Runnable
// new Reciver().start(); //extends Thread
} catch (IOException e) {
throw new RuntimeException(e);
}
//메세지 보내기 기능
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String sendMSG = tf.getText();
if(!sendMSG.equals("")){
System.out.println("입력됨!"+tf.getText());
out.writeUTF(nickname+":"+tf.getText());
tf.setText("");
scp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollBar verticalBar = scp.getVerticalScrollBar();
verticalBar.setValue(verticalBar.getMaximum());
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
});
}
private void arrange() {
add(scp, "Center");
add(tf, "South");
}
private void inflate() {
setTitle("Chatting Room");
setSize(450, 640);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(this);
setVisible(true);
}
class Reciver implements Runnable{
// class Reciver extends Thread{
DataInputStream in;
public Reciver(Socket socket) {
try {
in = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
while (in != null){
try {
String msg = in.readUTF();
//과제(수정) 프로그램안에서 띄우기
ta.append(msg+"\n");
ta.setCaretPosition(ta.getDocument().getLength());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
package p11_network;
import java.net.*;
import java.io.*;
import java.util.*;
public class Ex02TcpIpMultichatServer {
public static void main(String args[]) {
new Ex02TcpIpMultichatServer().start();
}
HashMap clients;
//동기화
Ex02TcpIpMultichatServer() {
clients = new HashMap();
Collections.synchronizedMap(clients);
}
//서버는 서버 소켓이 있어야함, 클라이언트는 소켓만 있어도 가능
public void start() {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(7777);
System.out.println("Server started...");
//서버는 무한적으로 돌아가야한다
while (true) {
socket = serverSocket.accept();
System.out.println("Connected from [" + socket.getInetAddress() + ":" + socket.getPort() + "]");
ServerReceiver thread = new ServerReceiver(socket);
thread.start();
}
} catch (Exception e) {
e.printStackTrace();
}
} // start()
void sendToAll(String msg) {
Iterator it = clients.keySet().iterator();
while (it.hasNext()) {
try {
DataOutputStream out = (DataOutputStream) clients.get(it.next());
out.writeUTF(msg);
} catch (IOException e) {
}
} // while
} // sendToAll
class ServerReceiver extends Thread {
Socket socket;
DataInputStream in;
DataOutputStream out;
ServerReceiver(Socket socket) {
this.socket = socket;
try {
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
}
}
public void run() {
String name = "";
try {
name = in.readUTF();
sendToAll("#" + name + " 님이 입장하셨습니다.");
clients.put(name, out);
System.out.println("현재 접속자 수: " + clients.size());
while (in != null) {
sendToAll(in.readUTF());
}
} catch (IOException e) {
// ignore
} finally {
sendToAll("#" + name + " is disconnected");
clients.remove(name);
System.out.println("Terminated from [" + socket.getInetAddress() + ":" + socket.getPort() + "]");
System.out.println("현재 접속자 수: " + clients.size());
} // try
} // run
} // ReceiverThread
} // class
package p07_Collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.function.IntFunction;
public class Ex10Generics {
public static void main(String[] args) {
// Generics 사용목적
//1) 형변환 코드를 생략하여 간결해짐.
//2) 타입의 안정성을 도모.
// ArrayList list = new ArrayList(); // 제네릭스 미사용
ArrayList<Card> list = new ArrayList(); //제네릭스 사용
list.add(new Card(7, "Spade", "rect"));
list.add(new Card(2, "Spade", 2));
list.add(new Card(3, "Spade", true));
list.add(new Card(4, "Spade", new Object()));
list.add(new Card(5, "Spade", "A"));
// Card card = (Card) list.get(0); // 제네릭스 미사용
Card card = list.get(0); // 제네릭스 사용
// 배열을 List 타입으로 변경하는 3가지 방법
// Card[] cards = list.toArray(new Card[list.size()]); //Java 8 이전
// Card[] cards = list.stream().toArray(Card[]::new); //Java 8 이후
// Card[] cards = list.toArray(Card[]::new); //Java 11 이후
Card[] cards = list.toArray(new IntFunction<Card[]>() { //Java 11 이후
@Override
public Card[] apply(int value) {
System.out.println(">>" + value); //0인 이유:
//배열의 길이가 0인 이유는 배열을 참조하기 위함.(null로 초기화하기도 함.)
return new Card[value];
}
});
Deck<Card> deck = new Deck<>();
deck.set(cards);
deck.print();
}
}
/*
class Card {
private int num; private String type;
public Card(int num, String type) {this.num = num;this.type=type;}
public String toString(){return num + "/" + type;}
}
*/
class Card<K, V, G> {
private K num;
private V type;
private G fig;
public Card(K num, V type, G fig) {
this.num = num;
this.type = type;
this.fig = fig;
}
public void setKVG(K num, V type, G fig) {
this.num = num;
this.type = type;
this.fig = fig;
}
public String toString() {
return num + "/" + type;
}
}
class Deck<T> {
T[] deck; // Card[] deck;
void set(T[] deck) {
this.deck = deck;
}
void print() {
for (int i = 0; i < deck.length; i++) {
if (i != 0) System.out.print(", ");
System.out.print(deck[i]);
}
System.out.println();
}
}
package p07_Collection;
public class Ex11GenericsSuperExtends {
public static void main(String[] args) {
Gen1 gen1 = new Gen1();
Gen2 gen2 = new Gen2();
Gen3 gen3 = new Gen3();
//<? super type>,<? extends type> //상속관계를 이용하여 타입을 제약
//Gen2의 조상이 Gen1, Gen1을 조상으로하는 하위 모든 자손 gen1, gen2, gen3
GenType<? super Gen2> genType = new GenType<>(gen3);
GenType<? extends Gen2> genType1 = new GenType<>(gen2);
// Gen2를 상속받는 하위 모든 자손 gen2, gen3
GenType<? extends Gen2> genType2 = new GenType<>(gen3);
//
GenType<?> genType3 = new GenType<>(new Object());
}
}
class Gen1 {
String name = "Gen1";
public String toString() {
return name;
}
}
class Gen2 extends Gen1 {
String name = "Gen2";
public String toString() {
return name;
}
}
class Gen3 extends Gen2 {
String name = "Gen3";
public String toString() {
return name;
}
}
class GenType<T>{
T obj;
public GenType(T obj){this.obj = obj;}
public void set(T obj){ this.obj = obj;}
public T get(){ return obj;}
}
package p10_Stream;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class Ex06FunctionPackage {
//일반적으로 자주 쓰이는 메서드 형식 4가지를
//@FunctionalInterface 형태로 만듬
public static void main(String[] args) {
//1.매개변수 없고 리턴타입이 있을 때
Supplier<Integer> supplier = new Supplier<Integer>() {
@Override
public Integer get() {
return (int) (Math.random() * 100) + 1;
}
};
supplier = () -> {
return (int) (Math.random() * 100) + 1;
};
supplier = () -> (int) (Math.random() * 100) + 1;
//2.매개변수 있고 리턴타입이 없을 때
Consumer<Integer> consumer = new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer + " ");
}
};
consumer = integer -> System.out.println(integer + " ");
//3. 매개변수도 있고 리턴타입도 있을 때
Function<Integer, Integer> function = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) {
return integer * 10;
}
};
function = integer -> integer * 10;
//4. 매개변수도 있고 리턴타입도 있는데 리턴 타입이 boolean일 때
Predicate<Integer> predicate = new Predicate<Integer>() {
@Override
public boolean test(Integer integer) {
return integer % 2 == 0;
}
};
predicate = integer -> integer % 2 == 0;
//응용
List<Integer> list = new ArrayList<>();
makeRandomList(supplier, list);
System.out.println(list);
printEven(predicate, consumer, list);
List<Integer> newList = doSomething(function, list);
System.out.println(newList);
}
private static <T> void makeRandomList(Supplier<T> supplier, List<T> list) {
for (int i = 0; i < 10; i++) list.add(supplier.get());
}
private static <T> List<T> doSomething(Function<T, T> function, List<T> list) {
List<T> tempList = new ArrayList<T>(list.size());
for (T item : list) tempList.add(function.apply(item));
return tempList;
}
private static <T> void printEven(Predicate<T> predicate, Consumer<T> consumer, List<T> list) {
for (T i : list) if (predicate.test(i)) consumer.accept(i);
System.out.println();
}
}
새로운 테이블 생성하기
alter session set "_ORACLE_SCRIPT" = true;
create user db7 IDENTIFIED by 1234 default tablespace USERS;
--권한 부여
grant connect, resource to db7;
테스트해서 성공하면 됨
create table memo(memo varchar2(20));
오라클 버전 확인
select *from v$version;
oracle 21c jdbc driver download
https://www.oracle.com/kr/database/technologies/appdev/jdbc-downloads.html
인텔리J에서 오라클 연동하기
연동시 경로가 안맞는 버그가 생길수 있어서 프로젝트안에 넣어줌
다운받은 .jar 를 추가해준다
package p12_database;
import java.sql.*;
public class DAOSet {
private Connection conn;
private PreparedStatement pstmt;
private Statement stmt;
private ResultSet rs;
public Connection connectDB() throws SQLException {
//String driver ="jdbc:mariadb://127.0.0.1:3306/db7"; //maria db
String driver = "jdbc:oracle:thin:@localhost:1521:xe"; //oracle
String user = "db7", pass = "1234";
conn = DriverManager.getConnection(driver, user, pass);
return conn;
}
public void closeDB() {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
System.out.println(conn.isClosed()?"접속종료":"접속중");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
package p12_database;
import java.sql.Connection;
import java.sql.SQLException;
public class DAOSetTest {
public static void main(String[] args) {
DAOSet daoSet = new DAOSet();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = daoSet.connectDB();
System.out.println(conn.isClosed()?"접속종료":"접속중");
} catch (ClassNotFoundException e) {
System.out.println("드라이버로딩 오류: "+e.getMessage());
} catch (SQLException e) {
System.out.println("접속 오류: "+e.getMessage());
}
finally {
daoSet.closeDB();
}
}
}
728x90
반응형
'PROGRAMING📚 > Java📑' 카테고리의 다른 글
Java::활용 - Stream (0) | 2024.07.05 |
---|---|
Java::Thread (0) | 2024.07.05 |
Java::활용 - List (0) | 2024.07.05 |
Java:: 입출력 Stream I/O (0) | 2024.06.27 |
Java :: 활용 -String (0) | 2024.06.25 |
댓글