Created
April 3, 2013 18:13
-
-
Save nurularifins/5303712 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.serverclient; | |
import java.io.BufferedWriter; | |
import java.io.IOException; | |
import java.io.OutputStreamWriter; | |
import java.io.PrintWriter; | |
import java.net.InetAddress; | |
import java.net.Socket; | |
import java.net.UnknownHostException; | |
import android.annotation.SuppressLint; | |
import android.app.Activity; | |
import android.os.Bundle; | |
import android.os.StrictMode; | |
import android.util.Log; | |
import android.view.View.OnClickListener; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import android.widget.TextView; | |
import android.view.View; | |
public class SocketClient extends Activity { | |
private Button bt; | |
private TextView tv; | |
private Socket socket; | |
private String serverIpAddress = "192.168.43.23"; | |
private static final int REDIRECTED_SERVERPORT = 5000; | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
bt = (Button) findViewById(R.id.myButton); | |
tv = (TextView) findViewById(R.id.myTextView); | |
con(); | |
try { | |
InetAddress serverAddr = InetAddress.getByName(serverIpAddress); | |
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT); | |
} catch (UnknownHostException e1) { | |
e1.printStackTrace(); | |
} catch (IOException e1) { | |
e1.printStackTrace(); | |
} | |
bt.setOnClickListener(new OnClickListener() { | |
public void onClick(View v) { | |
try { | |
EditText et = (EditText) findViewById(R.id.EditText01); | |
String str = et.getText().toString(); | |
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); | |
out.println(str); | |
Log.d("Client", "Client sent message"); | |
} catch (UnknownHostException e) { | |
tv.setText("Error1"); | |
e.printStackTrace(); | |
} catch (IOException e) { | |
tv.setText("Error2"); | |
e.printStackTrace(); | |
} catch (Exception e) { | |
tv.setText(e.getMessage().toString()); | |
e.printStackTrace(); | |
} | |
} | |
}); | |
} | |
@SuppressLint("NewApi") | |
public void con() { | |
if (android.os.Build.VERSION.SDK_INT > 9) { | |
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); | |
StrictMode.setThreadPolicy(policy); | |
} | |
try { | |
InetAddress serverAddr = InetAddress.getByName("serverIpAddress"); | |
socket = new Socket(serverAddr, 5000); | |
} catch (UnknownHostException e1) { | |
e1.printStackTrace(); | |
} catch (IOException e1) { | |
e1.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment