Android Socket Example
Android Socket Example
Download NOW!
Server.java:
001 package com.javacodegeeks.android.androidsocketserver;
002
import java.io.BufferedReader;
003
import java.io.IOException;
004 import java.io.InputStreamReader;
005 import java.net.ServerSocket;
006 import java.net.Socket;
007
008 import android.app.Activity;
import android.os.Bundle;
009 import android.os.Handler;
010 import android.widget.TextView;
011
012 public class Server extends Activity {
013
014 private ServerSocket serverSocket;
015
016 Handler updateConversationHandler;
017
Thread serverThread = null;
018
019 private TextView text;
020
021 public static final int SERVERPORT = 6000;
022
023 @Override
public void onCreate(Bundle savedInstanceState) {
024
025
super.onCreate(savedInstanceState);
026 setContentView(R.layout.main);
027
028 text = (TextView) findViewById(R.id.text2);
029
030 updateConversationHandler = new Handler();
031
032 this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
033
034
}
035
036 @Override
037 protected void onStop() {
038 super.onStop();
039 try {
serverSocket.close();
040 } catch (IOException e) {
041 e.printStackTrace();
042 }
043 }
044
class ServerThread implements Runnable {
045
046
public void run() {
047 Socket socket = null;
048 try {
049 serverSocket = new ServerSocket(SERVERPORT);
050 } catch (IOException e) {
e.printStackTrace();
051 }
052 while (!Thread.currentThread().isInterrupted()) {
053
054 try {
055
056 socket = serverSocket.accept();
057
058 CommunicationThread commThread = new CommunicationThread(socke
new Thread(commThread).start();
059
060 } catch (IOException e) {
061 e.printStackTrace();
062 }
063 }
}
064 }
065
066 class CommunicationThread implements Runnable {
067
068 private Socket clientSocket;
069
070 private BufferedReader input;
071
072 public CommunicationThread(Socket clientSocket) {
073
this.clientSocket = clientSocket;
074
075
try {
076
077 this.input = new BufferedReader(new InputStreamReader(this.clientS
078
079 } catch (IOException e) {
080 e.printStackTrace();
081 }
}
082
083
public void run() {
084
085 while (!Thread.currentThread().isInterrupted()) {
086
087 try {
088
089 String read = input.readLine();
090
091 updateConversationHandler.post(new updateUIThread(read));
092
} catch (IOException e) {
093 e.printStackTrace();
094 }
095 }
096 }
097
}
098
099
class updateUIThread implements Runnable {
100 private String msg;
101
102 public updateUIThread(String str) {
103 this.msg = str;
104 }
105
@Override
106 public void run() {
107 text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
108 }
109 }
110 }
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
6. Port Forwarding
In order to interconnect the programs in the two different emulators this is what
happens:
1. The Server program will open the port 6000 on emulator A. That means that
porst 6000 is open on the ip of the emulator which is 10.0.2.15.
2. Now, the client in emulator B will connect to the locahost, that is the
development machine, which is aliased at 10.0.2.2 at port 5000.
3. The development machine (localhost) will forward the packets to 10.0.2.15 :
6000
So in order to do that we have to do some port forwatding on the emulator. To do
that, run the Server Programm in order to open the first emulator:
Now, as you can see in the Window bar, we can access the cosnole of this emulator
at localhost : 5554. Press Windows Button + R, write cmd on the text box to open a
comman line. In order to connect to the emulator you have to do :
1 telnet localhost 5554
Example 2
Server side:
MainActivity.java
package com.blogspot.android_er.androidchatserver;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
List<ChatClient> userList;
ServerSocket serverSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
chatMsg = (TextView) findViewById(R.id.chatmsg);
spUsersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_drop
down_item);
spUsers.setAdapter(spUsersAdapter);
btnSentTo = (Button)findViewById(R.id.sentto);
btnSentTo.setOnClickListener(btnSentToOnClickListener);
infoIp.setText(getIpAddress());
}else{
Toast.makeText(MainActivity.this, "No user connected",
Toast.LENGTH_LONG).show();
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
ChatClient client = new ChatClient();
userList.add(client);
ConnectThread connectThread = new ConnectThread(client,
socket);
connectThread.start();
runOnUiThread(new Runnable() {
@Override
public void run() {
spUsersAdapter.notifyDataSetChanged();
}
});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Socket socket;
ChatClient connectClient;
String msgToSend = "";
@Override
public void run() {
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
dataInputStream = new
DataInputStream(socket.getInputStream());
dataOutputStream = new
DataOutputStream(socket.getOutputStream());
String n = dataInputStream.readUTF();
connectClient.name = n;
@Override
public void run() {
chatMsg.setText(msgLog);
}
});
while (true) {
if (dataInputStream.available() > 0) {
String newMsg = dataInputStream.readUTF();
if(!msgToSend.equals("")){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
userList.remove(connectClient);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
spUsersAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,
connectClient.name + " removed.",
Toast.LENGTH_LONG).show();
@Override
public void run() {
chatMsg.setText(msgLog);
}
});
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
chatMsg.setText(msgLog);
}
});
}
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
class ChatClient {
String name;
Socket socket;
ConnectThread chatThread;
@Override
public String toString() {
return name + ": " + socket.getInetAddress().getHostAddress();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.blogspot.android_er.androidchatserver.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Char Server"
android:textStyle="bold" />
<TextView
android:id="@+id/infoport"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic" />
<TextView
android:id="@+id/infoip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic" />
<Spinner
android:id="@+id/spusers"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/sentto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sent msg to individual user"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/chatmsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
sonic0002 2013-05-11 22:17:16 49,628 3
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
try {
// Create ServerSocket instance and bind it to port 9999
ServerSocket server = new ServerSocket(PORT);
while (true) {
Socket socket = server.accept();
// Get output buffer
BufferedWriter writer = new BufferedWriter(
new
OutputStreamWriter(socket.getOutputStream()));
// Write output
writer.write("这是一段来自服务器的问候:Hello 沃
德!");
writer.flush();
writer.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Client side:
com.example.socketdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
@SuppressLint("HandlerLeak")
public class SocketDemo extends Activity {
/** Called when the activity is first created. */
private Button btn_receive;
private TextView txt;
private String line;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControl();
}
@SuppressLint("HandlerLeak")
class ReceiverListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread() {
@Override
public void run() {
try {
// Create Socket instance
Socket socket = new Socket(HOST,
PORT);
// Get input buffer
BufferedReader br = new
BufferedReader(
new
InputStreamReader(socket.getInputStream()));
line = br.readLine();
br.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
}.start();
}
}
The effect:
<uses-permission android:name="android.permission.INTERNET">