«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

올해는 머신러닝이다.

java socket 프로그래밍(헤더/본문포함) 본문

자바/자바팁

java socket 프로그래밍(헤더/본문포함)

행복한 수지아빠 2011. 10. 27. 10:51

1.     Java Server

import! java.io.BufferedReader;

import! java.io.File;

import! java.io.FileOutputStream;

import! java.io.InputStreamReader;

import! java.net.ServerSocket;

import! java.net.Socket;

 

public class TCPServer implements Runnable{

public static final int serverPort = 10200;

@Override

public void run(){

       try{

       System.out.println("대기중..");

           ServerSocket serverSocket = new ServerSocket(serverPort);

             

           while(true)

           {

              Socket sock = serverSocket.accept();

              System.out.println("수신중....");

              try{

                  BufferedReader in = new BufferedReader(new

InputStreamReader(sock.getInputStream()));

                 String str = in.readLine();

                 System.out.println("수신중인 파일 이름 : " + str);

                 File f = new File("c:\\down\\", str+".jpg");

                 FileOutputStream output = new FileOutputStream(f);

                 byte[] buf = new byte[1024];                                       while(sock.getInputStream().read(buf)>0)

                 {

                    output.write(buf);

                    output.flush();

                 }

                 in.close();

                 output.close();

                 System.out.println(str+".jpg 수신완료");

             }

             catch(Exception e){

                 System.out.println("서버 에러!!");

                 e.printStackTrace();

             }

             finally{

                 sock.close();

             }

           }

       }

       catch(Exception e){

           e.printStackTrace();

       }

}

public static void main(String[] argv){

Thread doit = new Thread(new TCPServer());

       doit.start();

}

}

서버소켓을 생성하고 안드로이드 에뮬레이터에서 보내오는 스트림 데이터를 설정된 경로에FileOutputStream클래스를 이용하여 저장한다.

 

 

2.     Android Client

-       TCPClient.java

package sm.bit.sock;

 

import! java.io.BufferedWriter;

import! java.io.DataInputStream;

import! java.io.DataOutputStream;

import! java.io.File;

import! java.io.FileInputStream;

import! java.io.OutputStreamWriter;

import! java.io.PrintWriter;

import! java.net.InetAddress;

import! java.net.Socket;

 

public class TCPClient implements Runnable{

private static final String serverIP="192.168.34.52";

private static final int serverPort = 10200;

private String msg;

public TCPClient(String msg){

       super();

       this.msg = msg;

}

@Override

public void run(){

try{

           InetAddress serverAddr = InetAddress.getByName(serverIP);

           Socket sock = new Socket(serverAddr, serverPort);

           try{

            PrintWriter out = new PrintWriter(new BufferedWriter(new

OutputStreamWriter(sock.getOutputStream())), true);

               out.println(msg);

               out.flush();

                          

               DataInputStream dis = new DataInputStream(new

FileInputStream(new File("/mnt/sdcard/"+msg+".jpg")));

               DataOutputStream dos = new

DataOutputStream(sock.getOutputStream());

               byte[] buf = new byte[1024];

               while(dis.read(buf)>0)

               {

                  dos.write(buf);

                  dos.flush();

               }

               dos.close();

           }

           catch(Exception e){

               e.printStackTrace();

           }

           finally

           {

              sock.close();

           }

}

catch(Exception e){

             e.printStackTrace();

}

}

}

소켓을 생성하고 안드로이드 에뮬레이터의 sdcard 있는 사진 파일을 검색해서DataOutputStream 클래스로 패킷화 하여 소켓으로 전송한다.

 

-       Sock.java

package sm.bit.sock;

import! android.app.Activity;

import! android.os.Bundle;

import! android.view.View;

import! android.view.View.[안내]태그제한으로등록되지않습니다-xxOnClickListener;

import! android.widget.Button;

import! android.widget.EditText;

import! android.widget.TextView;

 

public class Sock extends Activity {

    private EditText myet;

    private TextView mytv;

    private Button mybtn;

    public String remsg;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

       

        myet = (EditText)findViewById(R.id.edit);

        mytv = (TextView)findViewById(R.id.text);

        mybtn = (Button)findViewById(R.id.sendbtn);

        mybtn.set[안내]태그제한으로등록되지않습니다-xxOnClickListener(new [안내]태그제한으로등록되지않습니다-xxOnClickListener(){

            @Override

           public void [안내]태그제한으로등록되지않습니다-xxonClick(View v){

                if((mybtn.getText().toString() != null)&&

(!mybtn.getText().toString().equals(""))){

                   TCPClient tp = new TCPClient(myet.getText().toString());

                   tp.run();

                     

                   mytv.setText(myet.getText().toString());

                   myet.setText("");

                }

            }

        });

    }

}

 


3.     실행 결과

-       Java

 

-       Android

 

 

첨부파일 [조별스터디 Android] 안드로이드 파일전송 - ja.doc


출처:http://blog.naver.com/marine694?Redirect=Log&logNo=110106773623