Wednesday, October 10, 2007

No. 1

A: How was your tirp to Thailand?
B: We had a good time there. We traveled all over the country and visited some fantastic attractions.
A: What was the accommodation like?
B: Excellent, everywhere we went. And the people were very nice.
A: Sounds perfect.
B: On the whole, it was. But, I had to make a couple of international phone calls fom a hotel, and I really had to pay through the nose for those.

1. How was...? == What ... was like?
2. pay through the nose for something

Sunday, September 30, 2007

Make a promise!!

1. Study english everyday!!
2. Read a book everyday!!
3. No absence in sport climbing class!!
4. Diet - Temperance & No coffee!!
5. Write four treatises
(4, October) A Study on Mobile UCC Transmission Model based-on P2P
(6, October) A Study on GridIR System Configuration with Web Crawler' Distributed Experiment
(Not decided) UI4GSD: User Interface for Grid Services Development
(Not decided) Design and Implementation of Remote Deployment Interface for Grid Services based-on Globus Toolkit 4.0.5

Monday, September 10, 2007

MultiThread Example

///////////////////////////////////////////////////////////////////////
1. RoseThread.java
///////////////////////////////////////////////////////////////////////

package thread;

//RoseThread.java
import java.util.Date ;

class RoseThread extends Thread {
String Result="" ;
public RoseThread(String str) {
super(str) ;
} // end RoseThread()

public void run() {
Date current= new Date() ;
for(int i=0;i<10;i++) {
System.out.println(i+" "+ getName()+ " " + current.getSeconds() ) ;
try {
sleep( (int)(Math.random() * 1000)) ;
} catch (InterruptedException e) {}
} // end for

Result = getName();
System.out.println("선택!! => "+ Result ) ;
} // end run()
} // end all

///////////////////////////////////////////////////////////////////////
2. LoveThread.java
///////////////////////////////////////////////////////////////////////
package thread;

class LoveThread {
public static void main (String args[]) {
new RoseThread("사랑한다").start() ;
new RoseThread("기다린다").start() ;
new RoseThread("포기한다").start() ;
}
}

Wednesday, September 5, 2007

쓰레드

Peer1,2 는 그대로.. Client만 쓰레드로 바꾸어줬음..근데 이렇게 하면 제대로 되기는하는데요..
첫번째줄이 만약 에러 나면 두번째줄 이 실행왠지 안되는거같아요...ㅠㅠ
그럼 쓰레드 만든게 아닌가요?ㅋ 어트케 테스트 해봐야할지요..ㅠㅠㅠㅠㅠㅠ


import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Client_Th {

static RandomAccessFile OutputFile;
static FileChannel OutputChannel;

class Client_thread extends Thread{

private Client_thread(String IP,int Port,int position,int length) throws IOException{

SocketAddress addr = new InetSocketAddress(IP,Port);
SocketChannel socket = SocketChannel.open(addr);
System.out.println("[peer socket]: "+ socket);
sendInfo(socket,position,length);
readSocket(socket,length,position);
closeSocketChannel(socket);
}

private void sendInfo(SocketChannel socket,int position,int length) throws IOException{

byte[] b = new byte[2];
b[0]= (byte) position;
b[1]= (byte) length;
ByteBuffer Info = ByteBuffer.allocate(b.length);
Info.put(b);
Info.flip();
socket.write(Info);
System.out.println("#write Info[To Peer)]:"+ b[0]+ " " + b[1]);
Info.clear();}

private void readSocket(SocketChannel socket,int length,int position) throws IOException{
//Peer로부터 전송된 파일 읽기
ByteBuffer readBuf = ByteBuffer.allocate(length);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read [From Peer]:" );
while(readBuf.hasRemaining()){
System.out.print((char)readBuf.get());
}
System.out.print("\n\n");
readBuf.flip();
writeFile(readBuf,position);
}

private void writeFile(ByteBuffer readBuf,int position) throws IOException{
//읽은 내용 파일에 쓰기
OutputChannel.position(position);
OutputChannel.write(readBuf);
readBuf.clear();
}

private void closeSocketChannel(SocketChannel socket) throws IOException{
socket.close();
}
}

private static void makeFileChannel(String filename) throws FileNotFoundException{
OutputFile = new RandomAccessFile(filename,"rw");
OutputChannel = OutputFile.getChannel();
}
public void send(String IP,int Port,int position,int length) throws IOException{

Client_thread ct = new Client_thread(IP,Port,position,length);
ct.start();
}

public static void main(String[] args) {
try{
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a_copy.txt";
makeFileChannel(filename);

new Client_Th().send("127.0.0.1",10001,10,110);
new Client_Th().send("127.0.0.1",10002,0,10);

}catch(Exception e){
System.out.println(e);
}finally{
try{
OutputFile.close();
OutputChannel.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}

}

Monday, August 27, 2007

작업 전송 문제 해결

1. 현재 작업 전송 방법 : 순차적인 방법
makeSocket("127.0.0.1",10003,10,110);
makeSocket("127.0.0.1",10002,0,10);
-> 위와 같은 전송 방법은 첫번째 전송에서 문제가 발생하면 두번째 전송을 수행하지 않음.
따라서 이를 쓰레드로 만들어서 처리함.(멀티쓰레드, 쓰레드풀)

2. 돌프야 어여 모바일쪽 서버 접속 프로그램 처리해야지?????

Sunday, August 26, 2007

Peer_1

Peer_2 도 똑같음..ㅋㅋ
토큰안하고 그냥 랭스랑 포지션 같이 보내는걸로 했어요..ㅋㅋ

import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Peer_1 {
static int Port = 10001;
static FileChannel InputChannel;
static RandomAccessFile InputFile;
static ServerSocketChannel server;
static ServerSocket serverSocket;
static boolean flag = false;
static int length = 0;
static int position = 0;

private static void makeSocket() throws IOException{
//소켓생성
server = ServerSocketChannel.open();
serverSocket = server.socket();
SocketAddress addr = new InetSocketAddress(Port);
serverSocket.bind(addr);
System.out.println("[Peer1]:" + server + "접속을 기다립니다");
SocketChannel socket = server.accept();
readInfo(socket);
sendFile(socket);
serverSocket.close();
}


private static void makeFileChannel(String filename) throws FileNotFoundException{
//File,Filechannel 생성
InputFile = new RandomAccessFile(filename,"rw");
InputChannel = InputFile.getChannel();
}

private static void readInfo(SocketChannel socket) throws IOException{
//Client로부터 요청된 position 읽기
ByteBuffer readBuf = ByteBuffer.allocate(3);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read[From Clent]:" );
while(readBuf.hasRemaining()){
System.out.print("Position :"+readBuf.get());
}
readBuf.flip();
System.out.print("\n");
byte[] b = new byte[2];
readBuf.get(b);
System.out.println("P:"+ b[0]+" s:"+ b[1]);
readBuf.clear();
position = b[0];
length = b[1];
}
private static void sendFile(SocketChannel socket) throws IOException{
//파일읽어 Clietn에게 전송하기
ByteBuffer writeBuf = ByteBuffer.allocate(length);
InputChannel.position(position);
InputChannel.read(writeBuf);
writeBuf.flip();
socket.write(writeBuf);
writeBuf.flip();
while(writeBuf.hasRemaining()){
System.out.print((char)writeBuf.get());
}
System.out.print("\n");
writeBuf.clear();
}

public static void main(String[] args){

try{
while(!flag){
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a.txt";
makeFileChannel(filename);
makeSocket();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
serverSocket.close();
server.close();
InputFile.close();
InputChannel.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}

Client

import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Client {
static RandomAccessFile OutputFile;
static FileChannel OutputChannel;

private static void makeSocket(String IP,int Port,int position,int length) throws IOException{

SocketAddress addr = new InetSocketAddress(IP,Port);
SocketChannel socket = SocketChannel.open(addr);
System.out.println("[peer socket]: "+ socket);
sendInfo(socket,position,length);
readSocket(socket,length,position);
closeSocketChannel(socket);
}

private static void sendInfo(SocketChannel socket,int position,int length) throws IOException{

byte[] b = new byte[2];
b[0]= (byte) position;
b[1]= (byte) length;
ByteBuffer Info = ByteBuffer.allocate(b.length);
Info.put(b);
Info.flip();
socket.write(Info);
System.out.println("#write Info[To Peer)]:"+ b[0]+ " " + b[1]);
Info.clear();}

private static void readSocket(SocketChannel socket,int length,int position) throws IOException{
//Peer로부터 전송된 파일 읽기
ByteBuffer readBuf = ByteBuffer.allocate(length);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read [From Peer]:" );
while(readBuf.hasRemaining()){
System.out.print((char)readBuf.get());
}
System.out.print("\n\n");
readBuf.flip();
writeFile(readBuf,position);
}

private static void makeFileChannel(String filename) throws FileNotFoundException{
OutputFile = new RandomAccessFile(filename,"rw");
OutputChannel = OutputFile.getChannel();
}

private static void writeFile(ByteBuffer readBuf,int position) throws IOException{
//읽은 내용 파일에 쓰기
OutputChannel.position(position);
OutputChannel.write(readBuf);
readBuf.clear();
}

private static void closeSocketChannel(SocketChannel socket) throws IOException{
socket.close();
}

public static void main(String[] args) {
try{
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a_copy.txt";
makeFileChannel(filename);
makeSocket("127.0.0.1",10001,10,110);
makeSocket("127.0.0.1",10002,0,10);
}catch(Exception e){
System.out.println(e);
}finally{
try{
OutputFile.close();
OutputChannel.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}

Thursday, August 23, 2007

ByteBuffer -> String Transformation Method

private void transfer(String test) {
ByteBuffer buffer = ByteBuffer.allocate(test.length());
buffer.put(test.getBytes());
String string = "";
for (int i = 0; i < buffer.limit()-1; i++) {
string += (char)buffer.get(i);
}
System.out.println(string);
}

StringTokenizer Example

import java.util.*;

import sun.security.action.GetBooleanAction;

public class StringTokenizerTest {
private String recvData = "";
private String[] info = new String[4];
public StringTokenizerTest(String recvData) {
this.recvData = recvData;

getPositionNLength(this.recvData);
}
private String[] getPositionNLength(String data){
int index = 0;
StringTokenizer st = new StringTokenizer(data, "/");
while(st.hasMoreTokens()) {
info[index] = st.nextToken();
index++;
}

for(int i = 0; i < info.length; i++) {
System.out.println(info[i]);
}
return info;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String sendData = "p/128/s/512";
new StringTokenizerTest(sendData);
}
}

Peer_2

length같이 보내서 Token하는거는 못했어요(position만 보낼수있음ㅋ)..ㅠㅠ
파일이 128까지라면 Client가
Peer_1한테 10~128까지..
Peer_2한테는 0~10까지 요청했어요..

import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Peer_2 {
static int Port = 10002;
static FileChannel InputChannel;
static RandomAccessFile InputFile;
static ServerSocketChannel server;
static ServerSocket serverSocket;
static boolean flag = false;

private static void makeSocket() throws IOException{
//소켓생성
server = ServerSocketChannel.open();
serverSocket = server.socket();
SocketAddress addr = new InetSocketAddress(Port);
serverSocket.bind(addr);
System.out.println("[Peer1]:" + server + "접속을 기다립니다");
SocketChannel socket = server.accept();
int position = readInfo(socket);
sendFile(socket,10,position);
serverSocket.close();
}


private static void makeFileChannel(String filename) throws FileNotFoundException{
//File,Filechannel 생성
InputFile = new RandomAccessFile(filename,"rw");
InputChannel = InputFile.getChannel();
}

private static int readInfo(SocketChannel socket) throws IOException{
//Client로부터 요청된 position 읽기
ByteBuffer readBuf = ByteBuffer.allocate(2);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read[From Clent]:" );
while(readBuf.hasRemaining()){
System.out.print("Position :"+readBuf.get());
}
System.out.print("\n");
readBuf.clear();
int position = readBuf.get();
return position;
}
private static void sendFile(SocketChannel socket,int length,int position) throws IOException{
//파일읽어 Clietn에게 전송하기
ByteBuffer writeBuf = ByteBuffer.allocate(length);
InputChannel.position(position);
InputChannel.read(writeBuf);
writeBuf.flip();
socket.write(writeBuf);
writeBuf.flip();
while(writeBuf.hasRemaining()){
System.out.print((char)writeBuf.get());
}
System.out.print("\n");
writeBuf.clear();
}

public static void main(String[] args){

try{
while(!flag){
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a.txt";
makeFileChannel(filename);
makeSocket();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
serverSocket.close();
server.close();
InputFile.close();
InputChannel.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}

Peer1

import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Peer_1 {
static int Port = 10001;
static FileChannel InputChannel;
static RandomAccessFile InputFile;
static ServerSocketChannel server;
static ServerSocket serverSocket;
static boolean flag = false;

private static void makeSocket() throws IOException{
//소켓생성
server = ServerSocketChannel.open();
serverSocket = server.socket();
SocketAddress addr = new InetSocketAddress(Port);
serverSocket.bind(addr);
System.out.println("[Peer1]:" + server + "접속을 기다립니다");
SocketChannel socket = server.accept();
int position = readInfo(socket);
sendFile(socket,128,position);
serverSocket.close();
}


private static void makeFileChannel(String filename) throws FileNotFoundException{
//file,channel 생성
InputFile = new RandomAccessFile(filename,"rw");
InputChannel = InputFile.getChannel();
}

private static int readInfo(SocketChannel socket) throws IOException{
//Client로부터 요청된 position 읽기
ByteBuffer readBuf = ByteBuffer.allocate(2);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read[From Clent]:" );
while(readBuf.hasRemaining()){
System.out.print("Position :"+readBuf.get());
}
System.out.print("\n");
readBuf.clear();
int position = readBuf.get();
return position;
}
private static void sendFile(SocketChannel socket,int length,int position) throws IOException{
//파일읽어 Clietn에게 전송하기
ByteBuffer writeBuf = ByteBuffer.allocate(length);
InputChannel.position(position);
InputChannel.read(writeBuf);
writeBuf.flip();
socket.write(writeBuf);
writeBuf.flip();
while(writeBuf.hasRemaining()){
System.out.print((char)writeBuf.get());
}
System.out.print("\n");
writeBuf.clear();
}

public static void main(String[] args){

try{
while(!flag){
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a.txt";
makeFileChannel(filename);
makeSocket();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
serverSocket.close();
server.close();
InputFile.close();
InputChannel.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}

Client

import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Client {
static RandomAccessFile OutputFile;
static FileChannel OutputChannel;

private static void makeSocket(String IP,int Port,int position,int length) throws IOException{

SocketAddress addr = new InetSocketAddress(IP,Port);
SocketChannel socket = SocketChannel.open(addr);
System.out.println("[peer socket]: "+ socket);
sendInfo(socket,position);
readSocket(socket,length,position);
closeSocketChannel(socket);
}

private static void sendInfo(SocketChannel socket,int position) throws IOException{
//Peer에게 position보내기
byte[] b = new byte[1];
b[0]= (byte) position;
ByteBuffer Info = ByteBuffer.allocate(2);
Info.put(b);
Info.flip();
socket.write(Info);
System.out.println("#write Info[To Peer)]:"+(byte)position);
Info.clear();
}

private static void readSocket(SocketChannel socket,int length,int position) throws IOException{
//Peer로부터 전송된 파일 읽기
ByteBuffer readBuf = ByteBuffer.allocate(length);
socket.read(readBuf);
readBuf.flip();
System.out.print("#read [From Peer]:" );
while(readBuf.hasRemaining()){
System.out.print((char)readBuf.get());
}
System.out.print("\n\n");
readBuf.flip();
writeFile(readBuf,position);
}

private static void makeFileChannel(String filename) throws FileNotFoundException{
//file,filechannel 생성
OutputFile = new RandomAccessFile(filename,"rw");
OutputChannel = OutputFile.getChannel();
}

private static void writeFile(ByteBuffer readBuf,int position) throws IOException{
//읽은 내용 파일에 쓰기
OutputChannel.position(position);
OutputChannel.write(readBuf);
readBuf.clear();
}

private static void closeSocketChannel(SocketChannel socket) throws IOException{
socket.close();
}

public static void main(String[] args) {
try{
String filename = "C:\\Documents and Settings\\mina\\test\\Buffer\\src\\a_copy.txt";
makeFileChannel(filename);
makeSocket("127.0.0.1",10001,10,128);
makeSocket("127.0.0.1",10002,0,10);
}catch(Exception e){
System.out.println(e);
}finally{
try{
OutputFile.close();
OutputChannel.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}

Wednesday, August 22, 2007

3253

/*
* Copyright 2000-2001 by Sun Microsystems, Inc.,
* 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
* All rights reserved.
*/

//package examples.helloworld;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class HelloWorld extends MIDlet implements CommandListener {
private Command exitCommand;
private TextBox tb;

public HelloWorld() {
exitCommand = new Command("Exit", Command.EXIT, 1);
tb = new TextBox("Hello MIDlet", "Hello, World!", 15, 0);
tb.addCommand(exitCommand);
tb.setCommandListener(this);
}

protected void startApp() {
Display.getDisplay(this).setCurrent(tb);
}

protected void pauseApp() {}
protected void destroyApp(boolean u) {}

public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}

파일 전송 사이트

1. http://blog.naver.com/leemazda?Redirect=Log&logNo=60010743904
2. http://blog.naver.com/mazester?Redirect=Log&logNo=60005202227
3. http://blog.naver.com/hypermin?Redirect=Log&logNo=70020492804
4. ByteBufferPool & ThreadPool
http://blog.naver.com/swucs?Redirect=Log&logNo=40003944682
5. http://blog.naver.com/knbawe?Redirect=Log&logNo=100004038472

Clent

//파일부분 전송해서 쓰는거 밖에 못해요..
2대 1 전송은 아직 하나도 못했음..ㅠㅠㅠ
서버쪽에서 또다른 클라이언트가 접속했을때
파일읽어오라고 어떻게 해야할까요?..
쓰레드를 써야하나요? 힘들어서 자요..ㅋㅋ

import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Client {
static RandomAccessFile InputFile;
static FileChannel InputChannel;
static int divSize = 128;

public static void main(String[] args) {

try{

InputFile = new RandomAccessFile("C:\\Documents and Settings\\mina\\test\\Random\\src\\d.txt","rw");
InputChannel = InputFile.getChannel();

SocketAddress addr = new InetSocketAddress("127.0.0.1", 10001);
SocketChannel socket= SocketChannel.open(addr);
System.out.println(socket);

//서버가 보내온 position읽기
ByteBuffer buf1 = ByteBuffer.allocate(2);
socket.read(buf1);
buf1.flip();
System.out.print("# socket read :");
while(buf1.hasRemaining()){
System.out.print("Piece :"+buf1.get());
}
buf1.clear();
int position = buf1.get();
//파일읽어 서버에게 전송하기
ByteBuffer buf2 = ByteBuffer.allocate(divSize);
InputChannel.position(position);
InputChannel.read(buf2);
buf2.flip();
socket.write(buf2);
buf2.flip();
while(buf2.hasRemaining()){
System.out.print((char)buf2.get());
}
buf2.clear();
}catch(Exception e){
System.out.println(e);
}
}
}

Server

import java.net.*;
import java.nio.channels.*;
import java.io.*;
import java.nio.*;

public class Server {
static FileChannel OutputChannel;
static RandomAccessFile OutputFile;
static int divSize = 128;

public static void main(String[] args){

try{

ServerSocketChannel server = ServerSocketChannel.open();
System.out.println("before "+server);
ServerSocket socket = server.socket();
SocketAddress addr = new InetSocketAddress(10001);
System.out.println("[Server]:접속을 기다립니다");
socket.bind(addr);
System.out.println("after " + server);
SocketChannel socketChannel = server.accept();

int position = 10;
//클라이언트에게 position 보내기
byte[] b = new byte[1];
b[0]= (byte) position;
ByteBuffer buf1 = ByteBuffer.allocate(2);
buf1.put(b);
buf1.flip();
socketChannel.write(buf1);
System.out.println("\n"+"# socket write : "+(byte)position);
buf1.clear();

//클라이언트로부터 전송된 파일 읽기
ByteBuffer buf = ByteBuffer.allocate(divSize);
socketChannel.read(buf);
buf.flip();
System.out.print("# socket read :");

//읽은 내용 파일에 쓰기
String filename = "C:\\Documents and Settings\\mina\\test\\Random\\src\\d_server.txt";
RandomAccessFile OutputFile = new RandomAccessFile(filename,"rw");
OutputChannel = OutputFile.getChannel();
OutputChannel.position(position);
OutputChannel.write(buf);
buf.flip();
while(buf.hasRemaining()){
System.out.print((char)buf.get());
}

}catch(Exception e){
System.out.println(e);
}
}
}

Tuesday, August 21, 2007

다음 작업

1. 돌프
우선, 모바일 에뮬레이터 띄워서 웹 사이트에 접속하는 프로그램을 한번 만들어봐라.
이건 처음에 본 모바일 책에도 있고,
아님 인터넷에서 찾던지,
아님 도서관에서 찾던지,...
찾아보면 소스가 꽤 많이 있을거야...
이부분에 관한 소스 만들어서 테스트 해보고 블로그에 올려놔라....

2. 강이방
이방은 파일 읽고 쓰는게 되니까....
다음으로 할일은 파일 전송하는거 다시 해보고(전송받을때 파일이름은 임의로 설정해라),
파일 전송이 잘되면, 전송하는 부분에 부분읽기/쓰기를 합해서 테스트 해봐라....
여기까지는 이미 다 끝난 부분이니까 금방할테고....

진짜 할일은 2대 1전송을 하는 것이다.
2개의 피어에서 같은 파일을 다운로드 할때,
부분읽기/쓰기를 활용해서 파일을 반씩 다운로드 받도록 하는 프로그램을 만들어봐라.
(그럼 요청을 반씩하면 되겠지??
1-50까지는 피어1에게 전송받고, 51-100까지는 피어2에게 전송받는...)
<--이해가 안가면 연락해라....

Monday, August 20, 2007

파일읽기쓰기

ㅋㅋㅋㅋ 잘했죠?

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.ByteBuffer.*;

public class Buffer {

static long filesize = 0;
static int divSize = 128;
static int pieceIndex = 0;
static FileChannel InputChannel = null;
static FileChannel OutputChannel = null;
static RandomAccessFile InputFile;
static RandomAccessFile OutputFile;

public static void makebuffer(FileChannel InputChannel,FileChannel OutputChannel,int position,int count)throws Exception{

ByteBuffer buf = ByteBuffer.allocate(divSize);
InputChannel.position(position);
InputChannel.read(buf);
buf.flip();

byte[] by = new byte[buf.limit()];
buf.get(by);
System.out.println(count + "번째 읽어온 부분:" + "\n" + new String(by) + "\n");

ByteBuffer buf2 = ByteBuffer.allocate(divSize);
buf2.put(by);
buf2.flip();
OutputChannel.position(position);
OutputChannel.write(buf2);

}

public static void read_write(RandomAccessFile InputFile ,RandomAccessFile OutputFile) throws Exception{

InputChannel = InputFile.getChannel();
OutputChannel = OutputFile.getChannel();

filesize = InputFile.length();
pieceIndex = (int)filesize/divSize;

if((int)filesize%divSize != 0){
pieceIndex = pieceIndex + 1;
}

System.out.println("fileSize :" + filesize + "\n" + "pieceIndex : " + pieceIndex + "\n" );

int position = 0;

for(int i = 0;i-pieceIndex;i++){
makebuffer(InputChannel,OutputChannel,position,i+1);
position += divSize;
}

}

public static void main(String[] args) throws Exception {
String filename = "C:\\workspace\\RandomAccess\\src\\a.txt";
String filename2 = "C:\\workspace\\RandomAccess\\src\\copy_a.txt";

try {
InputFile = new RandomAccessFile(filename,"rw");
OutputFile = new RandomAccessFile(filename2,"rw");

read_write(InputFile,OutputFile);

} catch(IOException ex) {
ex.printStackTrace();
} finally {
try {
InputChannel.close();
OutputChannel.close();
InputFile.close();
OutputFile.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}

Friday, August 17, 2007

부분읽기

이것도 아니죠?ㅋㅋ..다시 수정할게요..ㅋㅋ

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.ByteBuffer;

public class Part {
public static void main(String[] args) {
String filename = "C:\\Documents and Settings\\mina\\test\\Random\\src\\abcd.txt";
FileChannel InputChannel = null;
long filesize = 0;
int shareNum = 0;
int index = 0;
shareNum = 4;

try {
RandomAccessFile f = new RandomAccessFile(filename,"rw");
InputChannel = f.getChannel();

filesize = f.length();
index = (int) (filesize/shareNum);

int part1 = index+1;
int part2 = index*2+1;
int part3 = index*3+1;

ByteBuffer buf1 = ByteBuffer.allocate(index+1);
InputChannel.position(0);
InputChannel.read(buf1);
buf1.flip();

byte[] by = new byte[buf1.limit()];
buf1.get(by);
System.out.println("1번째 읽어온 부분:" + new String(by));

ByteBuffer buf2 = ByteBuffer.allocate(index);
InputChannel.position(part1);
InputChannel.read(buf2);
buf2.flip();

byte[] by2 = new byte[buf2.limit()];
buf2.get(by2);
System.out.println("2번째 읽어온 부분:" + new String(by2));


ByteBuffer buf3 = ByteBuffer.allocate(index);
InputChannel.position(part2);
InputChannel.read(buf3);
buf3.flip();

byte[] by3 = new byte[buf3.limit()];
buf3.get(by3);
System.out.println("3번째 읽어온 부분:" + new String(by3));

ByteBuffer buf4 = ByteBuffer.allocate(index+1);
InputChannel.position(part3);
InputChannel.read(buf4);
buf4.flip();

byte[] by4 = new byte[buf4.limit()];
buf4.get(by4);
System.out.println("4번째 읽어온 부분:" + new String(by4));

InputChannel.close();

} catch(IOException ex) {
ex.printStackTrace();
}
}
}

Thursday, August 16, 2007

부분 읽기/쓰기

파일을 읽기/쓰기 하는 것을 부분적으로 하려면,

1. 파일 크기를 읽어온 다음,
2. 파일 크기를 일정 단위로 나눈다. 예) 1024KB/256KB = 4
3. 그러면 읽어올 대상이 생긴다.
예) 4조각 ->
index 1: 0~256,
index 2: 257~512,
index 3: 513~ 768,
index 4: 769~1024
4. 읽기를 수행한 뒤에 콘솔에 프린트한다.

쓰기는 읽기 반대로 하면 된다.

Wednesday, August 15, 2007

부분읽기

얼만큼 읽어와야하는지 length를 정하는 방법을 몰라서
버퍼사이즈를 읽어올만큼만 할당해서 정해놓은 position에서
버퍼사이즈만큼만 읽어옴..-이렇게 짜는거 아니죠?ㅋㅋㅋ
그리고요.. 한글을 인식못해요..숫자랑 영어만..ㅋㅋ

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.ByteBuffer;

public class RandomAccess {
public static void main(String[] args) {
String filename = "C:\\Documents and Settings\\mina\\test\\Random\\src\\abcd.txt";
String filename2 = "C:\\Documents and Settings\\mina\\test\\Random\\src\\f.txt";
FileChannel outputChannel = null;
FileChannel InputChannel = null;

try {
RandomAccessFile f = new RandomAccessFile(filename,"rw");
RandomAccessFile f2 = new RandomAccessFile(filename2,"rw");
InputChannel = f.getChannel();
outputChannel = f2.getChannel();

int BufferSize = 5;
int BufferStart = 3;

ByteBuffer buf = ByteBuffer.allocate(BufferSize);
InputChannel.position(BufferStart);
InputChannel.read(buf);
buf.flip();

outputChannel.position(BufferStart);
outputChannel.write(buf);

buf.flip();
byte[] by = new byte[buf.limit()];
buf.get(by);
System.out.println(new String(by));

outputChannel.close();
InputChannel.close();

} catch(IOException ex) {
ex.printStackTrace();
}
}
}

RandomAccessFile - file write

1번:RandomAccessFile 이용해서 파일쓰기(Hello World!!추가하기)

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.ByteBuffer;

public class RandomAccess {
public static void main(String[] args) {
String filename = "C:\\Documents and Settings\\mina\\test\\Random\\src\\abcd.txt";
FileChannel outputChannel = null;
try {
String s = "Hello World!!";
byte[] by = s.getBytes();
ByteBuffer buf = ByteBuffer.allocate(by.length);
buf.put(by);
buf.clear();

RandomAccessFile f = new RandomAccessFile(filename,"rw");
outputChannel = f.getChannel();
outputChannel.position(f.length());
outputChannel.write(buf);
outputChannel.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
}

RandomAccessFile-method & StringTokenzer

* 파일 이름 전송하기 *
StringTokenizer class 이용
< API >:
http://blog.naver.com/wildxing?Redirect=Log&logNo=20037023803
import java.util.*;
캐릭터 라인을 토큰에 분할할 수 있음.

< 생성 >
StringTokenizer(String str)
StringTokenizer(String str,String delim)
delim : 단락 문자

< Method >
int countTokens() : 예외를 생성하지 않고 Tokenizer의 nextToken메소드를 호출할수 있는 회수를 계산
boolean hasMoreTokens() : Tokenizer의 캐릭터라인으로 이용할 수 있는 토큰이 아직 있는지 판정
boolean hasMoreElements() : hasMoreToken 메소드와 같은 값을 돌려줌
String nextToken() : 캐릭터라인 Tokenizer로부터 다음의 토큰을 돌려줌

<파일 이름 가져오기>
byte buf = new byte[512];
StringTokenizer strToken = new StringTokenizer(new String(buf, "KSC5601").trim());
//trim()은 앞뒤 공백제거,문장 중간의 공백은 제거하지 않음/
String header = strToken.nextToken();
String filename = strToken.nextToken();

*RandomAccessFile*
< API >: http://java.sun.com/j2se/1.4.2/docs/api/java/io/RandomAccessFile.html
< 생성 >RandomAccessFile(File file, String mode)
RandomAccessFile(String name, String mode)

< Method >
void close()
FileChannel getChannel()
FileDescriptor getFD()
long getFilePointer()
long length()
int read()
int read(byte[] b)
int read(byte[] b,int off,int len)
boolean readBoolean()
byte readByte()
char readChar()
double readDouble()
float readFloat()
void readFully(byte[] b)
void readFully(byte[] b, int off, int len)
int readInt()
String readLine()
long readLong()
short readShort()
int readUnsignedByte()
int readUnsignedShort()
String readUTF()
void seek(long pos)
void setLength(long newLength)
int skipBytes(int n)
void write(byte[] b)
void write(byte[] b, int off, int len)
void write(int b)
void writeBoolean(boolean v)
void writeByte(int v)
void writeBytes(String s)
void writeChar(int v)
void writeChars(String s)
void writeDouble(double v)
void writeFloat(float v)
void writeInt(int v)
void writeLong(long v)
void writeShort(int v)
void writeUTF(String str)

RandomAccessFile--Channel

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Read_Donhak {
public static void main(String[] args) throws FileNotFoundException {
File aFile = new File("c:\\Donhak.txt");
RandomAccessFile inFile = new RandomAccessFile(aFile, "rw");

// 파일 채널 객체
FileChannel inChannel = inFile.getChannel();// ByteBuffer 생성
ByteBuffer buf = ByteBuffer.allocate(1024);

try {
inChannel.read(buf);
byte[] add = buf.array();
String ttt = new String(add);
System.out.println(ttt);
} catch (IOException e) {
e.printStackTrace();
}
buf.clear();
System.exit(0);
}
}

Thursday, August 9, 2007

RandomAccessFile 처리

파일전송 부분은 내가 내일 학교가서 할테니까..잉...
RandomAccessFile 클래스 보면, position()과 length를 통해서
임의의 부분의 데이터를 읽어올수 있다.
이거나 한번 해봐라..잉...

Client

이름하는건 했는데요..근데 파일크기 비교하는 부분에서요 크기가 파일 저장되있는 글자수로 나와요
글구요.. 주석처리한부분이 어떤게 잘못된건지 모르겠어요 그부분안됨..ㅠㅠ
import java.net.*;
import java.io.*;

public class Client {
public static void main(String[] args) {
File cfl = null;
try{
Socket sock =new Socket("127.0.0.1",10001);
cfl = new File("C:\\Documents and Settings\\mina\\workspace\\Echo\\src\\abcd.txt");

BufferedReader fin =new BufferedReader(new FileReader(cfl));
//BufferedReader bin =new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
System.out.println("[Client]:파일명[" + cfl.getName() + "]보내기" );
DataInputStream bin = new DataInputStream(sock.getInputStream());

int len =0;
char[] buf = new char[512];
bout.write((int) cfl.length());//파일크기를 제일 먼저 보냄..
while((len =fin.read(buf))!= -1){
bout.write(buf,0,len);
bout.flush();
}
System.out.println("[Client]:파일보내기완료 !!");
/*같은 파일인지 확인하는 부분..서버에서 파일크기같으면 1을 보내서 잘보냈다고 전달해줌 아님 2전달..
int c =0;
if(bin != null){
c = bin.readInt();
if(c == 1){
System.out.println("SUCCESS!!");}
else{
System.out.println("Fail");}
}
*/
System.out.println("[Client]: [파일size] : "+ cfl.length());
//위 파일크기가 글자수가 나옴..ㅠㅠ이상함..

fin.close();
bin.close();
bout.close();
sock.close();
}catch(Exception e){
System.out.println(e);
}
}
}

Sever

import java.net.*;
import java.io.*;
public class Sever {
public static void main(String[] args){
File sfl = null;
try{
ServerSocket server =new ServerSocket(10001);
System.out.println("[Server]:접속을 기다립니다");
Socket sock =server.accept();
InetAddress inetaddr =sock.getInetAddress();
System.out.println("[IP]:"+inetaddr.getHostAddress()+" [PORT]:"+sock.getPort()+" 로부터 접속!!");
String fileName = inetaddr.getHostAddress()+"_"+ sock.getPort();
sfl = new File("C:\\Documents and Settings\\mina\\workspace\\Echo\\src\\",fileName+".txt");
BufferedReader bin =new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter fout = new BufferedWriter(new FileWriter(sfl));
DataOutputStream bout = new DataOutputStream(sock.getOutputStream());

char[] buf =new char[512];
int len =0;
if(bin != null){
while((len =bin.read(buf))!= -1){
fout.write(buf,1,len);
fout.flush();
}
System.out.println("[Server]:"+sfl.getName()+" 파일받기완료 "+ "\n\t"+" 파일크기:"+(int)buf[0]);
//buf[0]에는 전송받은 파일크기,

/*같은 파일인지 확인하는 부분..같은 파일이면 1을 보냄..아님 2보냄
long fileLength = sfl.length()-1;
if((int)fileLength == (int)buf[0]){
bout.writeInt(1);
System.out.println("[Server]:SUCCESS!!");
bout.flush();
}
else{
bout.writeInt(2);
System.out.println("[Server]:FAIL!!");
bout.flush();
}*/
}
fout.close();
bout.close();
bin.close();
sock.close();

}catch(Exception e){
System.out.println(e);
}
}
}

Wednesday, August 8, 2007

ServerSocket

서버에 저장할 파일명 IP:PORT 로 하는거랑 파일제대로 전송된건지 하는거랑 쪼개서 보내는건
아직 못했어요..ㅠㅠ 곧 할게요..ㅋㅋㅋ이거하는대도 무지 힘들었음..ㅠ

import java.net.*;
import java.io.*;
public class SeverSocket {
public static void main(String[] args){

File fl = null; //읽어온 내용 저장할 파일(blank.txt에 저장할것임(아무내용도 없어야함))
try{

ServerSocket server =new ServerSocket(10001);
System.out.println("접속을 기다립니다");
Socket sock =server.accept();
InetAddress inetaddr =sock.getInetAddress();
System.out.println(inetaddr.getHostAddress()+"로부터 접속했습니다");
InputStream in =sock.getInputStream();
OutputStream out =sock.getOutputStream();
fl = new File("C:\\Documents and Settings\\mina\\workspace\\Echo\\src\\blank.txt");
//파일이름은 클라이언트 IP:PORT 이므로 inetaddr.getHostAddress() + sock.getPort()+ ".txt"
BufferedInputStream bin = new BufferedInputStream(in);
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(fl));

int len =0;
if(bin != null){
while((len =bin.read()) != -1){
bout.write(len);
bout.flush();
}
System.out.println("[Server]:파일받기완료");
/*파일전송 성공시 or 실패시
if(){
out.write("success!!");
out.flush();
}
else{
out.write("fail!!");
out.flush();
}
*/
}
bout.close();
bin.close();
sock.close();
}catch(Exception e){
System.out.println(e);
}
}
}

ClientSocket

import java.net.*;
import java.io.*;

public class ClientSocket {
public static void main(String[] args) {
File fr = null;
try{
Socket sock =new Socket("127.0.0.1",10001);
fr = new File("C:\\Documents and Settings\\mina\\workspace\\Echo\\src\\abcd.txt");
BufferedInputStream bin = new BufferedInputStream( new DataInputStream( new FileInputStream(fr)));
BufferedOutputStream bout = new BufferedOutputStream( new DataOutputStream( sock.getOutputStream() ));
System.out.println(" [Client]:파일명[ " + fr.getName() + " ]보내기 시작" );
int len =0;
while((len =bin.read()) != -1){
bout.write(len);
System.out.println("[Client]:" + (char)len );
bout.flush();
}
System.out.println("[Client]:보내기완료" );
bin.close();
bout.close();
sock.close();
}
catch(Exception e){
System.out.println(e);
}
}

}

Tuesday, August 7, 2007

파일 전송 테스트

* 파일전송*
# 서버1 to 클라이언트 1
1. 서버 - 서버는 전송되는 파일을 받아서 임의의 디렉토리에 파일을 저장한다.
- 파일전송이 완료되면 "SUCCESS OR FAILURE"메세지를 보낸다.
- 파일 이름: 요청한 클라이언트의 IP:PORT번호로 저장(127.0.0.1:7000)
2. 클라이언트 - 파일 전송을 전송하고 전송여부에 대한 메세지를 받는다.
- 받은 메세지는 콘솔창에 출력한다.

#서버1 to 클라이언트 n
가능?????????????????????

Sunday, August 5, 2007

MIDlet/추상&인터

*MIDlet 프로그램의 생명주기
-PAUSED : MIDlet이 초기화 되었거나 멈추고 있는 상태.
-ACTIVE : MIDlet이 실행되는 경우.
-DESTROYED : MIDlet이 사용하는 모든자원을 해제하는 단계.

MIDlet은 JAM과 서로 메시지를 주고받으면서 동작함. 휴대폰내의 JAM은 모든 MIDlet을 실행하고 중지키기고 없애는 역할을 하는 중요한 프로그램이다.
*JAM(java application manager)의 기능
-가져오기(retrieval) : 웹사이트에서 MIDlet을 다운로드하는 기능
-설치(installation) : 다운로드한 MIDlet을 휴대폰에 설치하는 기능
-실행(launching) : MIDlet을 실행하고 중지/없애는 기능
-버전 관리 : 설치된 MIDlet을 새로운 버전으로 업그레이드
-삭제(removal) : 설치된 프로그램을 삭제하는 기능

*추상 클래스와 인터페이스

추상클래스 : 추상메소드가 하나라도 있는 클래스
extends를 이용해서 추상 메소드를 구현함.
=>추상 클래스의 예
public abstract class Test{ //추상 클래스를 포함 클래스
public void sayHello(){ } //일반 메소드
public void sayHi(){ } //일반 메소드
public abstract void sayHowareyou(); //추상 메소드
} //추상 메소드인 경우 abstract 붙여야 함.

인터페이스 : 구현자체가 전혀 없는 순수한 추상 메소드로만 이루어져 있는 클래스
implements를 이용해서 추상 메소드를 구현함.
=>인터페이스의 예
public interface IRemoteControl{
void powerOn(); //추상 메소드
void powerOff(); //추상 메소드
void channelUp(); //추상 메소드
} //메소드에 굳이 abstract 붙일 필요 없다!!

Thursday, August 2, 2007

EclipseME설치

1.eclipseme 라는 플러그인설치eclipseme.feature_1.7.3
2.eclipse 실행 -> window>Preferences 선택
3.(왼쪽트리에있는)Java항목 확장-> build Path 선택-> 오른쪽의 Folders버튼 선택
4.[Help > Software updates > Find and install]선택 -> 두번째 "Search for new features to install"버튼 선택 next버튼!!
5.New Remote Site..클릭-> Name : eclipseME Update Site
URL : http://www.eclipseme.org/updates/
6.finish -> eclipseme 체크하고 -> next -> next -> finish
7.install 클릭 -> 재시작할지 여부 물으면 yes 눌러 eclipse 다시 시작함
8.Window > Preferences 에 J2ME 항목 추가되었다면 ok
9.J2ME>Device Management > Import..클릭 > C:\\WTK22 선택 > Refresh > finish
10.Java > Debug > Suspend execution on uncaught exceptions 와 Suspend execution on compilation errors 의 체크박스를 해제한다. 다음으로 Debugger time out = 15000설정
11.HelloWorld 파일 작성해보기 File > New > Project 선택
12.J2ME > J2ME Midlet Suite 를 선택 -> Next
13.Project name: HelloWorld 하고 finish
14.src 폴더항목위에 New > File 클릭하여 파일명 HelloWorld.java 하여 finish
15.코드작성하기..
16.Run > Run 선택

J2ME wireless Toolkit

1.J2ME wireless Toolkit 설치파일 실행(최신버젼 2.2)
2.약관동의>yes> Next> Next> Next> Next> 완료!!
3.시작메뉴에서 새로운 프로그램이 깔린다(J2ME wireless Toolkit2.2)
4.Run MIDP Application 실행
5.설치디렉터토리 : C:\WTK22\apps\Games\bin\Games.jad 선택하고 Run 클릭
6.휴대폰이 화면에 출력되면 완료!!

helloworld

SCJP

1. SCJP 5.0 시험

- 시험 문항 : 72문항(객관식/단답식)
- 합격 점수 : 43문항 이상
- 시험 시간 : 175분
- 응시료 : 200,000원
- 시험 신청 : http://www.suntraining.co.kr/jsp/certification/exam/info.jsp
- 자료 관련 : http://www.forcert.com/sun/sun.html

2. MCDS 일정
1)배경지식 습득 :8월 1일 ~ 13일
java programing- stream(파일 입출력,메모리),thread & 동기화,기본 메소드
책 : 열혈강의, 휴대폰이용한 모바일 자바프로그래밍
java network programing - 소켓,TCP,UDP
책: 자바 IO & NIO,
J2ME(KVM) - 책: 휴대폰이용한 모바일 자바 프로그래밍
무선 자바프로그래밍(with J2ME)
XML(이것도 해야하는 건가요?ㅋㅋ)
servlet
JDBC- 쿼리처리문, DB연동
bittoreent protocol - 소스분석하기

2)설계 : 8월 14일 ~ 18일
3)구현 : 8월 19일 ~ 25일
4)테스트 및 수정 : 8월 26일 ~ 28일
5)보고서 작성 : 8월 29일 ~ 30일

Monday, July 30, 2007

8월 계획

1. SCJP 5.0 시험
- 시험 일정
- 시험시 필요한 것들(비용/장소/날짜 등등)
- 기출문제(최신)

2. MCDS(Mobile Contents Delivery System)
- 일정 잡기(월/주/일별로 해야할일)
- J2ME/Java Network Programming/Servlet&JSP Programming/JDBC Programming
- 이클립스에서 J2ME 환경 구성(테스트 요구)
- 추계학술대획 계획(잘되면 학술대회 논문으로 낼수도 있을듯...)
- 책구입(Java IO & NIO 네트워크프로그래밍, 모바일 프로그래밍, 기타등등)

3. 추가적인 자료
- http://sourceforge.net/projects/bitext (다운받아서 소스 분석하자!!)

Thursday, July 26, 2007

공지 사항

1. SCJP 5.0 시험에 관한 사항 알아보기
2. 일요일에 자바 시험(즉, 책 한권 다 읽기: GUI부분 제외)
개념, 프로그래밍
3. 이클립스에서 J2ME 개발환경 설치 방법

Project: Contents Delivery Service in Wireless Environment

프로젝트 제목은 "무선환경에서의 컨텐츠 전송 서비스"로 정했다.
제목을 이렇게 정하는 것이 맞는지 모르겠지만... (추후에 다시 생각해보자)

요구사항
0. BitExt 프로토콜 이용: BitTorrent Protocol 기반
1. J2ME 프로그래밍
- 휴대폰을 위한 모바일 자바 프로그래밍 : 이클립스 기반의 J2ME,WIPI,게임 프로그래밍
- 무선자바프로그래밍(WIRELESS JAVA PROGRAMMING WITH J2ME)
2. 네트워크 프로그래밍 - Java IO & NIO 한빛미디어
3. Servlet/JSP 프로그래밍 - 도서관, 인터넷
4. XML 프로그래밍 - 도서관, 인터넷
5. 데이터베이스 프로그래밍 - 도서관, 인터넷

다음 사항에 대한 부분을 나눠서 하기로 하자.
0. BitExt 프로토콜 : ㅡㅡ
1. J2ME, Servlet/JSP, DATABASE 프로그래밍: 강이방, 돌프
2. 네트워크, XML 프로그래밍: ALL

스케줄
미정 ????????????????????????????????????????

Wednesday, July 18, 2007

Hak's Homework

1. 예외 처리하는 부분에 대해서 정리
2. 소켓 프로그래밍 정리
- 간단한 에코 서버/클라이언트 구현(책보고...)
- nio 정리(tcp/udp)
3. 이클립스에서 J2ME 개발 환경 구성

Friday, July 13, 2007

MultiThread


Multi Thread
스레드란 ‘메서드가 동시에 실행되는것‘인데 이건 동시에 메서드작업이 진행된다는 의미이다. 여러개의 스레드가 동시에 작업이 진행될때 문제가 되는것이 바로 공유자원의 문제이다.
사용할수있는 자원은 한 개인데 그것을 여러개의 스레드가 동시에 이용하려고 할때 공유자원에 문제가 생긴다.
즉, 화장실은 한 개인데 것도 공용화장실이 한 개인데 기다리는사람이 3명일 경우 한명이 들어가면 나올때 까지 기다려야하는데 기다리지 않고 들어가면 문제가 발생하는것이다.
결국 기다리게 만드는 것이 해결책이라 할수 있겠다.
화장실에 들어가서 문을 잠그면 되는데 그것이 메모리에 락(Lock)을 거는 방법인데,한개의 스레드가 공유자원을 다 쓸때 까지 다른스레드들을 대기시키는 것이다.
이렇게 순서대로 사용하게하는기법을 동기화(Synchronization)라고 한다.
즉 줄서기인것이다

import java.io.*;
import java.util.*;

class Test{ //공유할자원을 한개 생성할 클래스
private int memory=100; //공유자원인 메모리

public int getMemory(){ //값을계산해서 변경할 메소드생성
return this.memory;
}
public void setMemory(int memory){ //계산된공유자원 저장할 메소드
this.memory=memory;
}
public void addMemory(int add){ //메모리에 값 더할 메소드
int m = this.getMemory(); //설정되어 있는값을 읽어들임 **중요부분**
try{
Thread.sleep(3000); //3초후에 동작
}catch(Exception e){
e.printStackTrace();
}
this.setMemory(m+add); //3초후에 메모리설정값에 add값을 더해서 변경
}
public void minusMemory(int min){ //메모리에 값을 뺄 메소드
int n = this.memory;
try{
Thread.sleep(200); //0.2초 후에 동작
}catch(Exception e){
e.printStackTrace();
}
this.setMemory(n-min); //0.2초 후에 메모리 설정값에 min값을 빼서 변경
}
}
class Donhak extends Thread{ //값을 더할스레드 생성
public void run(){
MultiThread.Test2.addMemory(50); //공유메모리의 50값을 더함
System.out.println("거기에50더하기 "+ MultiThread.Test2.getMemory()); //더해진 값을 출력
}
}
class Mina extends Thread{ //값을 빼는 스레드 생성
public void run(){
MultiThread.Test2.minusMemory(50); //공유메모리의 50값을 뺌
System.out.println("50빼기 "+ MultiThread.Test2.getMemory()); //빼진 값을 출력
}
}
public class MultiThread {
public static Test Test2 = new Test(); //Test와 같은 객체 Test2생성

public static void main(String[] args)throws Exception{ //메인 메소드
Donhak d = new Donhak(); //start를 할 객체 생성
Mina m = new Mina(); //start를 할 객체 생성
d.start(); //Donhak쓰레드 동작
try{
Thread.sleep(200);
}catch(Exception e){
e.printStackTrace();
}
m.start(); //Mina 스레드 동작
}
}

////////////////////////출력물///////////////////////////////
50빼기 50
거기에50더하기 150


이렇게 하면 Donhak이 **중요부분** 에서 100의 값을 읽어온후 3초간 기다린다.
그사이에 0.2초후에 Mina가 동작하는데 0.2초후에 100의 값을 읽어서 50을 뺀다.
그리고 설정값을 100에서 50으로 바꿔주는데, Donhak은 바뀐 50값에서 50을 더하는게
아니라 그전에 읽어들인 100의 값에서 50을 더하기 때문에 150의 값을 출력하게 된다
결국 공유자원에서의 순서의 문제로 오류가 발생한다. 은행에서 이럴경우 큰일난다.

####해결책#####
public synchronized void addMemory(int add){ //synchronized 메서드로 생성해서
//이메소드 안에서 생성되는 모든변수에 Lock가 걸리게 한다
int m = this.getMemory();
try{
Thread.sleep(3000);
}catch(Exception e){
e.printStackTrace();
}
this.setMemory(m+add);
}
public void minusMemory(int min){
synchronized(this){ //{}안에 현재 클래스에 사용된 맴버변수에 대한 동기화가 보장된다
int n = this.memory;
try{
Thread.sleep(200);
}catch(Exception e){
e.printStackTrace();
}
this.setMemory(n-min);
}
}

이렇게 synchronized 메소드를 사용해 addMemory에서 공유자원을 묶어줘야
Donhak이 작업을 할 3초를 기다린후에 Mina가 작업을해서 100에서 50을 더한수에
50을 빼게 된다.
//////////결과물////////
거기에50더하기 150
50빼기 100
}

Wednesday, July 11, 2007

STUDY1 : Multi-Thread Programming

To do list
First, What is the Multi-Thread Programming?
Second, How to wirite the Multi-Thread Program?

Thread.

//Runnable을 구현해서 만드는 스레드(스레드를 생성하는 방법)

class Top implements Runnable{ //Top로 인터페이스 생성 Runnable은 하나의
매소드(run())밖에 없는 인터페이스
public void run(){ //스레드가 동작시 작동하는 부분 start로 호출
for(int i=0; i<10; i++) //
System.out.print(i+"\t"); //
}
}
public class ThreadMain{ //
public static void main(String[] args){ //
System.out.println("프로그램 시작"); //스레드 시작전
Top t = new Top(); //Top형의 객체생성
Thread thd = new Thread(t); // Thread클래스로 스레드를만들때
//Runnable을 구현한 Top형의 객체를 넣어주고 만듬
thd.start(); //run()으로 독립적으로 스레드 동작시킴
System.out.println("프로그램 종료"); //스레드 동작후
}
}
//결과물은 프로그램시작->프로그램 종료->123456789 순서로 나온다 이유는
//프로그램 시작,과 종료가 출력되고난뒤에 스레드 작업이 진행되어서
//main도 하나의 스레드로 동작하다가 다른 스레드를 동작시키고 있어서
라인순으로 진행되지 않았다.

//Thread를 상속하는 스레드 만들기(Thread 상속)

class DerivedThread extends Thread{ //Thread를 직접 상속하는 클래스 생성

public void run(){ //스레드동작시 run의 재정의
for(int i=0; i<10; i++)
System.out.print(i+"\t");
}
}
public class DerivedThreadMain{ //스레드 생성할 클래스생성
public static void main(String[] args){
System.out.println("프로그램 시작"); //스레드 동작전
DerivedThread d = new DerivedThread(); //재정의된 DerivedThread형 객체생성
d.start(); //run동작
System.out.println("프로그램 종료"); //스레드 동작후
}
}
//Thread 클래스를 상속하는 것과 Runnable 인터페이스를 구현해서 하는것에는 큰 차이가 없는데 //인터페이스를 사용해서 하는이유는 내가 만든 클래스가 다른클래스를 상속했을 경우 자바에서는 다중상속이 //불가하기 때문에 Thread를 상속할수 없다 그러므로 인터페이스를 이용하여 Thread를 구현하는 방법을 사용한다.

thread

/* Runnable을 이용한 Thread */
//인터페이스 Runnable를 구현하여 run()재정의
//메인 메소드와 Top에 있는 run()메소드 동시에 작동

class Top implements Runnable{
//클래스 Top은 인터페이스 Runnable을 구현 - Runnable은 run()메소드 가지고 있음
public void run(){
//run()메소드 재정의
System.out.println("Runnable : Thread run!!");
//스레드 작동하는지 확인할 문자열 출력
}
}

public class Thread_1{
//스레드 생성할 클래스
public static void main(String args[]){ //메인 메소드
System.out.println("Thread start!!"); //문자열 출력
Top t = new Top();
//Top 형의 객체 생성 - Runnable을 구현하는 객체
Thread thd = new Thread(t);
//Thread 형의 객체 생성 (생성자에 Top형 객체생성한 것을 넣어줌)
thd.start();
//스레드 시작 - run()동작
System.out.println("Thread exit!!");
//문자열 출력
}
}

=================================================

/* 상속을 이용한 Thread */
//Thread 클래스를 직접 상속받아 run()메소드를 정의
//메인 메소드와 Top1에 있는 run()메소드 동시에 작동

class Top1 extends Thread {
//Thread 상속받는 클래스 Top1
public void run(){
//run()정의
System.out.println("Inheritance : Thread run!!");
//스레드 작동하는지 확인할 문자열 출력
}
}

public class Thread_2{
//스레드 생성할 클래스
public static void main(String[] args) {
//메인 메소드
System.out.println("Thread start!!");
//문자열 출력
Top1 t = new Top1();
//Top1형 객체 생성
t.start();
//스레드 작동 시킬 start()호출- Runnable을 이용한 방법과는 다르게
//Thread를 상속 받았기때문에 Thread 객체 생성할 필요없이 바로 start()호출가능
System.out.println("Thread end!!");
//문자열 출력
}
}

Tuesday, July 10, 2007

Homework 2

How to make a Thread Programming...

it has two mrthods.
1. uses the Runnable interface inheritance
2. uses the Thread Class inheritance

you have to write a two Thread programs and must comment all program source code line by line.

deadline : July. 11. 2007

Monday, July 9, 2007

JDBC Programming - login

Requirements:
1. input ID, Password

2. compares inputted id with ids from table of user in DATABASE
ex) select id from user;
and check the inputted id
ex)if (inputted id == ids[xx])

3. if inputted id exists,
you have to get a password which is matched inputted id.
ex)select password from user where id='inputted id';

3.1 if inputted password is vaild,
and you just have to print a success message "Login Success".

3.2 if not,
just print a failure message "Your password is wrong~~!!.
And input your password again."

3.3 and if re-inputted password is vaild,
just print "Login Success".

4. if not,
just print a failure message "You have to register".

Sunday, July 8, 2007

과제

접근제한자
public - 같은 클래스,같은 패키지,상속받은클래스,관계없는 클래스에서 전부사용가능하다
protected-public과 같고 관계없는 클래스에서 사용불가
package-같은 클래스와 같은 패키지 내에서만 사용가능
private-같은 클래스내에서만 사용가능

인터페이스-상수들과 추상메소드들의 집합
실체화 되지 않으며, 메소드는 기본public으로 공용가능하고 추상메소드를 구현해서 인터페이스를 구현,특히 특정 인터페이스를 구현한다고 선언했으면 인터페이스의 모든 메소드에대한 정의를 제공해야함

추상클래스
정의가 없는 한개이상의 추상메소드를 포함 but 객체를 생성할수 없음

추상메소드를 가진다는면에서 인터페이스와 추상클래스가 유사하나, 추상클래스는 인터페이스와 다르게 추상메소드가 아닌 메소드를 포함가능하고 상수 말고도 데이터선언도 포함할수 있다.

this - 자기자신을 가리킴.하나의 인스터스를 가리키는 자기 자신을 리턴할때사용
super - 부모 클래스를 가리키는 참조.super() 부모클래스 생성자가 호출된다

과제1

1. 자바에서 접근 제한자의 의미?
접근제한자로서는 public,protected,private,package 이 네가지가 있다.
public은 현재 클래스,다른 클래스,다른파일등에서도사용할 수 있다.
protected는 자신의 클래스와 상속 관계의 클래스, 동일한 파일, 동일한 폴더에서만 사용할 수 있다.
private는 자신의 클래스 내부에서만 사용하도록 제한한다.
package는 접근제한자를 사용하지 않는 형태로서 자신의 클래스와 동일한 파일에서사용되도록 제한한다.

2. 추상 클래스와 인터페이스의 의미?
추상 클래스는 객체를 발생시키지 못하는 것으로 몸체가 없는 메소드를 가진 클래스를 말하며 직접 객체를 발생시킬 필요가 없고 상속에 의해서 하위클래스만 제어할 목적이면 추상클래스를 사용한다.
인터페이스는 몸체 없는 메소드의 집합으로만 되어 있는 클래스로 자바는 다중 상속을 지원하지 않지만 인터페이스를 이용하면 다중 상속의 개념을 지원 할 수 있다.

3. this와 super의 의미?
this : 클래스내에서 메소드의 변수와 지역변수의 이름이 같을 경우 this를 사용해서 구별한다.
super: 자식 클래스가 부모클래스를 상속받았을 때 자식 클래스에서 부모클래스를 재정의 하면 부모클래스의 메소드는무시된다. 그때 부모클래스의 변수를 참조할 수 있게 해주는 것이 super이다.

Saturday, July 7, 2007

과제 1

1. 자바에서 접근 제한자의 의미?
2. 추상 클래스와 인터페이스의 의미?
3. this와 super의 의미?

Wednesday, July 4, 2007

제 7회 자바 공모전 안내


1. 공모전 안내 홈페이지 주소
http://www.jco.or.kr/competition/competitionInfo.jsp

2. 참가 자격
일반부 : SW개발자, SW개발업체, 단체 또는 일반인(개인, 공동, 단체 출품 가능)
학생부 : 중.고.대학(원)생(개인, 공동, 단체 출품 가능)
※ 공히 개인 또는 팀으로 참여 가능하며, 현재 휴학중인 경우도 가능

3. 출품 대상
가. 일반 소프트웨어부분
- 시스템소프트웨어, 인터넷, 응용소프트웨어, 컴퓨터게임, 네트워크, 정보보호SW 컴퓨터통신, DB, 교육, 기타 소프트웨어
- Java 기술을 이용하여 개발한 개발한 애플리케이션 또는 웹애플리케이션 전 분야
- 다른 기술을 포함할 수 있으나 Java 기술을 중심으로 개발
나. 공개 소프트웨어 부분
-시스템 소프트웨어, 미들웨어 및 응용 소프트웨어 등 공개 소프트웨어
다. 컴포넌트 부분
-시스템 소프트웨어, 미들웨어 및 응용 소프트웨어 등 컴포넌트 소프트웨어

4. SOFTEXPO2006 대한민국 S/W 공모대전 1차 심사 통과 작품 ======================================================
접수번호 작 품 명
-------- ------------------------------------------------------------------------
2006-105 ESBoiler
2006-109 지식기반 교육 솔루션(KEDU)
2006-111 인터액터(InterActor)
2006-114 TigrisBPM
2006-116 gPAMS(Geo Percet Area Monitoing System)
2006-117 LYCAS(Life cYcle Cost Analysis System for bridge design)
2006-118 플라잉팝콘 6.0 (멀티미디어 콘텐츠 저작도구)
2006-119 FlexMF Framewokr for FA
2006-120 BlueLens
2006-121 IO Insight for SOM
2006-128 "미로트랩"
2006-129 맵피MXT(TPEG 버전)
2006-135 인터넷노드- 홈미디어 시스템
2006-140 3Txer: 치열교정 치료계획 수립 및 치료장치 설계용 프로그램
2006-141 PowerMill 기반의 자유곡면 가공용 CAPP 시스템: Trucess CAPP
2006-143 맞춤가발 제작을 위한 3차원 두상 측정CAD/CAM 시스템
2006-144 웹 기반 마이크로 머시닝 서비스 (MIMS: Micro Machining Service)
2006-146 제품모델 스마트 인터페이스(Product Model Based Smart Interface)
2006-505 Master Quiz (문제제작 및 강의 저작툴)
2006-507 Mozzarto Music Workstation
2006-516 I-CAD (Industrial Computer-Aided Fault Diagnosis)
2006-520 uSNAP IDE(Ubiquitous Sensor Network Application Programs IDE)
2006-523 얼굴인식을 이용한 RFID 출입인증 시스템
2006-542 워터마킹을 이용한 문화제 컨턴츠의 저작권 보호
2006-543 Design Information Reusing
2006-544 노래에서 반주를 자동으로 생성하는 SmartComposer
2006-550 TCP/IP기반 버스위치 정보 안내 시스템
2006-552 English Input Interface
2006-560 MC World2006-563 홈미디어 서버
2006-566 Wimbie
2006-570 "Any Language, Any Device"를 위한 통합 소프트웨어 개발 솔루션(SKUVM)
2006-580 Movable Agent System on P2P(AHRA Framework)
2006-584 ALE based RFID Middleware
2006-585 Web2.0 Migration Framework(Tool)
2006-588 WAY(길)
2006-597 USN과 gateway를 이용한 DTV
2006-600 IDEG-MeshGen version 1.0
2006-601 객체지향 자동화 설계도구
2006-602 수정된 격자구성 기법을 이용한 자동 유한요소생성 프로그램
-------- ------------------------------------------------------------------------

Tuesday, July 3, 2007

휴대폰을 위한 모바일 자바 프로그래밍 : 이클립스 기반의 J2ME,WIPI,게임 프로그래밍

이 책의 특징
- 무선 통신과 모바일 프로그래밍의 기본 원리를 쉽게 설명합니다
- 휴대폰에서 동작하는 프로그램을 초보자가 이해하기 쉽게 설명하고 있으며, 프로그램 소스를 미리 실행해볼 수 있습니다
- 모든 프로그램은 자바의 새로운 프로그래밍 환경인 이클립스(Eclipse) 환경에서 실행됩니다
- 모바일 자바 프로그래밍의 기본 원리를 설명하며, 모바일 게임, 모바일 가계부 등 상용 프로그램 수준의 프로그램 소스를 제공합니다
- 재미있고 다양한 모바일 게임 프로그램 소스를 제공합니다
- WAP 프로그래밍의 기본 원리와 상용 프로그램 수준의 프로그램 소스를 제공합니다
- 모든 프로그램은 일반 휴대폰에서 바로 실습하고 쉽게 익힐 수 있도록 구성되어 있습니다- 책에 수록된 다양한 모바일 자바 및 WAP 프로그램을 부록 CD에서 제공합니다। - 책 내용에 관한 업데이트 사항이나 FAQ, Q&A, 소스 프로그램 등을 웹 사이트(www.myhome.naver.com/ javanese)에서 제공합니다.

Friday, June 29, 2007

Rss and Atom in Action: Building Applications with Blog Technologies

About the Author:
Dave Johnson started blogging in 2002 using Java-based blogging software that he developed called Roller. Roller now drives the ground-breaking employee blogs at Sun Microsystems, is used by thousands of bloggers on JRoller.com and other sites, and is a successful open source project. He lives in Raleigh, North Carolina.

Book Description:
RSS and Atom in Action is organized into two parts. The first part introduces the blog technologies of news feed formats and publishing protocols-the building blocks. The second part shows how to put to those blocks together to assemble interesting and useful blog applications. In keeping with the behind Manning's "In Action" series, this book shows the reader, through numerous examples in Java and C#, how to parse Atom and RSS format newsfeeds, how to generate valid newsfeeds and serve them efficiently, and how to automate blogging via web services based on the new Atom protocol and the older MetaWeblog API. The book also shows how to develop a complete blog client library that readers can use in their own applications. The second half of the book is devoted to a dozen blog apps-small but immediately useful example applications such as a community aggregator, a file distribution newsfeed, a blog cross-poster, an email-to-blog gateway, Ant tasks for blogging softwarebuilds, and more.