티스토리 뷰


Server.java



package com.example.testscoket;


import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;


import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;


public class Server extends Activity {


private static final int PORT = 5555;

private Socket socket;

private ServerSocket ss;

private DataInputStream is;

private DataOutputStream os;

private Handler hd;


private TextView message;

private EditText et;

private Button send, start;

private String writeMsg, readMsg;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.server);


hd = new Handler();


message = (TextView) findViewById(R.id.stv2);

et = (EditText) findViewById(R.id.set1);

send = (Button) findViewById(R.id.sbt1);

start = (Button) findViewById(R.id.start1);


send.setOnClickListener(new View.OnClickListener() {


@Override

public void onClick(View v) {


new Thread(new Runnable() {


@Override

public void run() {

writeMsg = et.getText().toString();

try {

os.writeUTF(writeMsg);

os.flush();

} catch (IOException e) {

e.printStackTrace();

}

}

}).start();

}

});


start.setOnClickListener(new View.OnClickListener() {


@Override

public void onClick(View v) {

// TODO Auto-generated method stub


start.setText("서버 가동");

new Thread(new Runnable() {


@Override

public void run() {

// TODO Auto-generated method stub


try {

ss = new ServerSocket(PORT);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

// 서버소켓 생성 실패

}


// 리슨

try {

socket = ss.accept();

is = new DataInputStream(socket.getInputStream());

os = new DataOutputStream(socket.getOutputStream());

hd.post(new Runnable() {


@Override

public void run() {

// TODO Auto-generated method stub

start.setText(socket.getInetAddress()

.getHostName() + "가 접속");

message.setText(socket.getInetAddress()

.getHostAddress());

}

});

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

// 접속과정에서 문제가 생김

}


while (true) {

try {

readMsg = is.readUTF();

// is.read(buffer);

hd.post(new Runnable() {


@Override

public void run() {

// TODO Auto-generated method stub

start.setText("데이터수신");

// message.setText(buffer.toString());

message.setText(readMsg);

}

});

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


}).start();

}

});

}

}



댓글
댓글쓰기 폼