SPRING :: NOTE
[android] C 서버와 소켓통신 본문
반응형
MainActivity.java
package com.example.sockest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
private String return_msg;
private EditText mEt;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
public void initData()
{
mEt = (EditText) findViewById(R.id.EditText01);
}
public void onClickBtn(View v)
{
Toast toast = Toast.makeText(getApplicationContext(), mEt.getText().toString(), 0);
toast.show();
TCPclient tcpThread = new TCPclient(mEt.getText().toString());
Thread thread = new Thread(tcpThread);
thread.start();
}
private class TCPclient implements Runnable
{
private static final String serverIP = "서버 아이피주소 입력(000.000.000.000)";
private static final int serverPort = 9999; //포트번호
private Socket inetSocket = null;
private String msg;
// private String return_msg;
public TCPclient(String _msg)
{
this.msg = _msg;
}
public void run()
{
// TODO Auto-generated method stub
try
{
Log.d("TCP", "C: Connecting...");
inetSocket = new Socket(serverIP ,serverPort );
//inetSocket.connect(socketAddr);
try
{
Log.d("TCP", "C: Sending: '" + msg + "'");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(inetSocket.getOutputStream())), true);
out.println(msg);
BufferedReader in = new BufferedReader(
new InputStreamReader(inetSocket.getInputStream()));
return_msg = in.readLine();
Log.d("TCP", "C: Server send to me this message -->"
+ return_msg);
}
catch (Exception e)
{
Log.e("TCP", "C: Error1", e);
}
finally
{
inetSocket.close();
}
}
catch (Exception e)
{
Log.e("TCP", "C: Error2", e);
}
}
}
}
activity_main.xml
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<android:id="@+id/EditText01" android:layout_width="fill_parent" android:layout_height="wrap_content">
<button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" android:onclick="onClickBtn">
</linearlayout>
manifast.xml
- 인터넷 사용 권한 추가
<uses-permission android:name="android.permission.INTERNET"/>
반응형
'Development Language > JAVA · ANDROID' 카테고리의 다른 글
[ANDROID] Custom ListView (커스텀 리스트뷰) Footer를 이용한 더보기 구현 (0) | 2016.06.08 |
---|---|
[안드로이드] 뒤로가기(Back 버튼) 두번 눌러 앱 종료하기 (0) | 2016.06.08 |
[ANDROID] 파일 생성 및 저장 (4) | 2016.05.27 |
[ANDROID] 현재시간(Local Time) 가져오기 (0) | 2016.05.27 |
[android] 파일명 변경 (0) | 2016.05.19 |
Comments