티스토리 뷰
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();
}
});
}
}
'공부 > android' 카테고리의 다른 글
안드로이드 기기간 소켓 통신하기 - 기타 코드 (1) | 2013.08.16 |
---|---|
안드로이드 기기간 소켓 통신하기 - 서버 코드 (1) | 2013.08.16 |
안드로이드 기기간 소켓 통신하기 - 양방향 (16) | 2013.08.16 |
onDraw (0) | 2012.11.19 |