Socket
Socket是用来进行网络通信的,并且也可以用来实现跨进程间的通信,只是服务器和主机都在同一台手机上了
服务端:
ServerSocket mServerSocket = new ServerSocket(port);
Socket socket = mServerSocket.accept();// 代码运行到这里了,会等待客户端的连接
第一行是申明了服务器和它的端口号,第二行就是等待客户端从port端口来连接服务器,连接成功了就会获得一个socket
客户端:
Socket socket = new Socket("localhost", port);
使用ip地址和端口号去连接,连接成功了就可以获得一个socket
数据传输:
连接成功过后,在服务端和客户端都会获得一个socket的对象,这个对象可以让我们获得连接的信息和和输入输出流,我们只需要往输出流中写入数据,对方就能通过输入流读取到数据。至于数据怎么写、怎么定义、怎么解析,那就是自己的设计或者协议的问题了。接下来我们看一个demo
SocketServicer.java
package com.fht.ada.socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
public class SocketServicer extends android.app.Service {
private static final String TAG = "Socket";
private ServerSocket mServerSocket;
private static final int port = 44534;
private ExecutorService mExecutorServicePool;
public SocketServicer() {
try {
mServerSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
// new 线程池
mExecutorServicePool = Executors.newFixedThreadPool(5);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.i(TAG, "start SocketServicer");
// 启动服务器的时候 我们就启动一个线程,里面有一个Socket等待远程的连接
new Thread() {
@Override
public void run() {
// 这里采用while循环,是为了可以让多个客户端一起连接进来
while (true) {
try {
Log.i(TAG, "mServerSocket 服务已经启动,正在等待连接");
Socket socket = mServerSocket.accept();// 代码运行到这里了,会等待客户端的连接
// 我们把socket放进线程池中进行管理
mExecutorServicePool.execute(new SocketHandler(socket));
Log.i(TAG, "mServerSocket 连接上了一个");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
// SocketHandler用来处理每一个连接的socket
class SocketHandler implements Runnable {
private Socket mSocket;
public SocketHandler(Socket socket) {
mSocket = socket;
}
@Override
public void run() {
try {
InputStream in = mSocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
OutputStream out = mSocket.getOutputStream();
while (true) {
String inputData = bufferedReader.readLine();
String reply = mReplyText[point];
SystemClock.sleep(1000);
point++;
point=point%mReplyText.length;
out.write((reply + "\n").getBytes());
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
int point = 0;
String[] mReplyText = new String[] { "把喜欢两字去掉才真是造孽", "唉,毕竟不是亲生的……", "成鸡思汉", "嗯,给你一头母猪,明年的肉价就能下跌!", "叫犯贱" };
}
ClientActivity.java
package com.fht.ada.socket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import com.fht.ada.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
public class ClientActivity extends Activity {
private static final String TAG = "Socket";
private static final int port = 44534;
private TextView mTextView;
private EditText mEditText;
private BufferedReader mBufferedReader;
private OutputStream mOutputStream;
private ScrollView mScrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_client_socket);
Intent socketServicer = new Intent(this, SocketServicer.class);
this.startService(socketServicer);// 启动服务器
mTextView = (TextView) this.findViewById(R.id.show_chat);
mEditText = (EditText) this.findViewById(R.id.input_message);
mScrollView = (ScrollView) this.findViewById(R.id.scroll_view);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
connectService();
mEditText.setText(mIntputText[0]);
}
String[] mIntputText = new String[] { "我喜欢上了一个比我小6岁的女孩,还在上初中,真是造孽啊", "我把我家的狗给揍了!地震它也不告诉我,平时叫得那么欢,刚才地震时竟像没事似的在窝里睡觉!",
"老婆生了个女娃,非常可爱,求各位帮爱女起个有气势的名字,鄙人姓成", "给我一个女人,我就能创造出一个民族!", "分手后的思念不叫思念" };
int point = 0;
public void sendMessage(View view) {
final String inputText = mEditText.getText().toString();
point++;
point = point % mIntputText.length;
mEditText.setText(mIntputText[point]);
new Thread() {
@Override
public void run() {
try {
mOutputStream.write((inputText + "\n").getBytes());
mOutputStream.flush();
Log.i(TAG, "client:" + inputText);
show("client:2016-6-10:\n " + inputText + "\n");
String replyText = mBufferedReader.readLine();
Log.i(TAG, "server:" + replyText);
show("server:2016-6-10:\n " + replyText + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void connectService() {
new Thread() {
public void run() {
// 我们在onStart()方法中去连接服务器
while (true) {
try {
Socket socket = new Socket("localhost", port);
InputStream in = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
mBufferedReader = new BufferedReader(inputStreamReader);
mOutputStream = socket.getOutputStream();
break;
} catch (Exception e) {
e.printStackTrace();
}
}
};
}.start();
}
public void show(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(TAG, mTextView == null ? "null" : "no null");
mTextView.append(s);
int offset = mTextView.getMeasuredHeight() - mScrollView.getHeight();
mScrollView.scrollTo(0, offset);
}
});
}
}
activity_client_socket.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/input_message"
android:layout_alignParentTop="true" >
<TextView
android:id="@+id/show_chat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" />
</ScrollView>
<EditText
android:id="@+id/input_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignTop="@+id/send_message"
android:layout_toLeftOf="@+id/send_message"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/send_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="sendMessage"
android:text="发送" />
</RelativeLayout>
AndroidManifes.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fht.ada"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.fht.ada.socket.ClientActivity"
android:label="Socket Client"
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.fht.ada.socket.SocketServicer"
android:process=":socket" >
<intent-filter>
<action android:name="com.fht.ada.socket.SocketServicer" />
</intent-filter>
</service>
</application>
</manifest>
至此,socket就实现了进程间的通信了