public
class
MainActivity
extends
AppCompatActivity {
OutputStream os;
InputStream is;
Socket socket;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
final
netthread thread =
new
netthread();
thread.start();
send_btn.setOnClickListener(
new
View.OnClickListener() {
@Override
public
void
onClick(View view) {
String stringdata=
"1234568"
+send_data.getText().toString();
Log.d(
"보낼데이터:"
,stringdata);
thread.send();
}
});
}
@Override
protected
void
onDestroy() {
super
.onDestroy();
try
{
if
(os !=
null
) {
os.flush();
}
if
(socket !=
null
) {
socket.close();
}
}
catch
(IllegalArgumentException e){}
catch
(IOException e) {
e.printStackTrace();
}
}
class
netthread
extends
Thread{
public
netthread(){
try
{
Log.d(
"들어오나?"
,
"보자"
);
}
catch
(Exception e){
}
}
public
void
run(){
request();
}
private
void
request(){
try
{
Log.d(
"소켓통신:"
,
"소켓"
);
socket =
new
Socket(
"192.168.0.13"
,
3333
);
Log.d(TAG,
"server connected"
);
is=socket.getInputStream();
os=socket.getOutputStream();
new
ReadThread(socket).start();
}
catch
(UnknownHostException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
}
public
void
send() {
new
Thread(
new
Runnable() {
@Override
public
void
run() {
if
(os!=
null
) {
try
{
String stringdata=
"12345678"
+send_data.getText().toString();
Log.d(
"소켓보낼데이터:"
,stringdata);
byte
[] data=stringdata.getBytes();
int
cnt=data.length;
byte
[] sendingdata=
new
byte
[cnt+
1
];
for
(
int
i=
0
;i<cnt;i++){
sendingdata[i]=data[i];
}
sendingdata[cnt]=
0x0d
;
os.write(sendingdata);
Log.d(TAG, stringdata);
send_data.setText(
""
);
log_save(stringdata,
"send"
);
}
catch
(IOException e) {
e.printStackTrace();
Log.d(TAG,
"send IOE"
);
}
}
}
}).start();
}
public
class
ReadThread
extends
Thread{
public
Socket socket;
public
ReadThread(Socket socket){
this
.socket = socket;
}
@Override
public
void
run() {
while
(socket.isConnected()) {
byte
[] buffer =
new
byte
[
128
];
int
count =
0
;
if
(socket !=
null
) {
try
{
String tmp;
count = is.read(buffer);
tmp =
new
String(buffer,
0
, count,
"utf-8"
);
Log.d(
"받은 데이터:"
,tmp);
read_data.setText(
" 받은데이터:"
+tmp);
log_save(tmp,
"read"
);
}
catch
(IOException e) {
e.printStackTrace();
Log.d(TAG,
"ReadThread IOE"
);
break
;
}
}
}
}
}