티스토리 뷰


Client.java


package com.example.testscoket;


import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.InetAddress;

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 Client extends Activity {


private static String IP = "192.168.0.1";

private static final int PORT = 5555;

private Socket socket;

private DataInputStream is;

private DataOutputStream os;

private Handler hd;

private String writeMsg, readMsg;


private TextView message;

private EditText et, ip;

private Button send, access;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.client);


hd = new Handler();

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

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

access = (Button) findViewById(R.id.access1);

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

ip = (EditText) findViewById(R.id.cet2);

ip.setText(IP);


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

}

});

access.setOnClickListener(new View.OnClickListener() {


@Override

public void onClick(View v) {


access.setText(IP + "로 접속");

IP = ip.getText().toString();

new Thread(new Runnable() {


@Override

public void run() {

try {

socket = new Socket(InetAddress.getByName(IP), PORT);

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

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

} catch (IOException e) {

e.printStackTrace();

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

}


while (true) {

try {

readMsg = is.readUTF();

hd.post(new Runnable() {


@Override

public void run() {

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

message.setText(readMsg);

}

});

} catch (IOException e) {

e.printStackTrace();

}

}

}

}).start();

}

});

}

}



댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
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
글 보관함