Android手机的应用,除了它的手机功能之外,另外一个吸引人的地方在于它的开放性,这一点iphone无法比拟,至少iphone太多商业化气息。如同当年windows95一样,android为我们开启另一扇交流之窗,而要实现交流,socket通信必不可少。java在socket通信方面上已经有了很好的范例,我只是抛砖引玉,将其引入到android之中,疏漏之处在所难免,很多地方也值得深思与考量,高手不必拍砖,可跳过此文。下面,用敲门的方式演示Android如何实现套接字的通信。
本例实现功能如下:
Server端开启服务
Client端发起链接请求,并向Server端发送数据
Server端响应请求,并在Server显示,向Client端返回数据
Client端接收Server的数据并显示
Server端:
package com.android.Yao;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class YaoChatServer extends Thread {
private YaoChatServer() throws IOException {
CreateSocket();
//创建Socket服务器
}
public void run() {
Socket client;
String txt;
try {
while (true)
//线程无限循环,实时监听socket端口
{
client=ResponseSocket();
//响应客户端链接请求。。
while(true)
{
txt=ReceiveMsg(client);
System.out.println(txt);
//链接获得客户端发来消息,并将其显示在Server端的屏幕上
SendMsg(client,txt);
//向客户端返回消息
if(true)break;
//中断,继续等待链接请求
}
CloseSocket(client);
//关闭此次链接
}
}
catch (IOException e) {
System.out.println(e);
}
}
private ServerSocket server = null;
private static final int PORT = 5000;
private BufferedWriter writer;
private BufferedReader reader;
private void CreateSocket() throws IOException
{
server = new ServerSocket(PORT, 100);
System.out.println("Server starting..");
}
private Socket ResponseSocket() throws IOException
{
Socket client = server.accept();
System.out.println("client connected..");
return client;
}
private void CloseSocket(Socket socket) throws IOException
{
reader.close();
writer.close();
socket.close();
System.out.println("client closed..");
}
private void SendMsg(Socket socket,String Msg) throws IOException
{
writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
writer.write(Msg+"\n");
writer.flush();
}
private String ReceiveMsg(Socket socket) throws IOException
{
reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
System.out.println("server get input from client socket..");
String txt="Sever send:"+reader.readLine();
return txt;
}
public static void main(final String args[]) throws IOException {
YaoChatServer yaochatserver = new YaoChatServer();
if (yaochatserver != null) {
yaochatserver.start();
}
}
}
Client端:
package com.android.Yao;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.UnknownHostException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class YaoChatRoomAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatroom);
findviews();
setonclick();
}
private EditText chattxt;
private TextView chattxt2;
private Button chatok;
public void findviews()
{
chattxt = (EditText)this.findViewById(R.id.chattxt);
chattxt2 = (TextView)this.findViewById(R.id.chattxt2);
chatok = (Button)this.findViewById(R.id.chatOk);
}
private void setonclick()
{
chatok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
connecttoserver(chattxt.getText().toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void connecttoserver(String socketData) throws UnknownHostException, IOException
{
Socket socket=RequestSocket("192.168.0.107",5000);
SendMsg(socket,socketData);
String txt = ReceiveMsg(socket);
this.chattxt2.setText(txt);
}
private Socket RequestSocket(String host,int port) throws UnknownHostException, IOException
{
Socket socket = new Socket(host, port);
return socket;
}
private void SendMsg(Socket socket,String msg) throws IOException
{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write(msg.replace("\n", " ")+"\n");
writer.flush();
}
private String ReceiveMsg(Socket socket) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String txt=reader.readLine();
return txt;
}
}
通过上边的例子,本人通过一些转换,实现了Android与CSharp Server的通讯方法。原理没有太大差异,仅仅是应用的方法稍有不同。
CSharp Server 源代码:
01.TcpClient ConnectedClient = ServerListener.AcceptTcpClient();
02.
03.NetworkStream netStream = ConnectedClient.GetStream();
04.
05.BinaryReader br = new BinaryReader(netStream);
06.
07.byte[] tempByte = new byte[8192];
08.
09.tempByte = br.ReadBytes(8192);
10.
11.string RecevieString = System.Text.Encoding.Default.GetString(tempByte);
对上边的源代码做一些介绍:
通过TcpListener获得的Client信息创建一个TcpClient对象。
1.TcpClient ConnectedClient = ServerListener.AcceptTcpClient();
从TcpClient对象中提取NetworkStream对象,其目的是建立Socket数据流。
1.NetworkStream netStream = ConnectedClient.GetStream();
建立BinaryReader对象为刚刚创建的NetworkStream提供一个接口,借助于这个接口可以非常方便的读取信息。
1.BinaryReader br = new BinaryReader(netStream);
读取Stream中的byte array数据,转化为string字符串。
1.byte[] tempByte = new byte[8192];
2.
3.tempByte = br.ReadBytes(8192);
4.
5.string RecevieString = System.Text.Encoding.Default.GetString(tempByte);
Android Client 源代码:
这个Android Client所应用的方法与前面例子中有很大区别,请各位特别注意(通过本人的反复验证,这个算是Java 与CSharp间可行的通讯方法)。
1.String message = "AndroidRes,Where is my Pig (Android)?";
2.Socket socket = new Socket("192.168.0.149", 51706);
3.OutputStream ops=socket.getOutputStream();
4.DataOutputStream dos=new DataOutputStream(ops);
5.dos.write(message.getBytes());
6.dos.close();
对上边的源代码做一些介绍:
同样是建立Socket对象。
1.Socket socket = new Socket("192.168.0.149", 51706);
根据Socket对象创建OutputStream对象,根据名称可以很容易的理解这个对象的目的,它是建立一个输出的NetworkStream。
1.OutputStream ops=socket.getOutputStream();
DataOutputStream类似于BinaryWriter,是为OutputStream建立一个接口,可以通过这个接口向Socket另外一端写数据。
1.DataOutputStream dos=new DataOutputStream(ops);
最后这两行代码是实施写的过程。
1.dos.write(message.getBytes());
2.dos.close();
以上就是为大家提供的Android与PC间通讯的方法,,如果你有更巧妙或者更方便的方法,希望能与大家共同分享!