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();
}
}
}
}