您的位置:首页 > 移动开发 > Android开发

Android socket通信

2016-06-01 23:38 423 查看
(一)服务器端

TCPDesktopServer.java


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPDesktopServer implements Runnable{
public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 1818;
public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true) {
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("S: Received: '" + str + "'");
} catch(Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}

public static void main (String a[]) {
Thread desktopServerThread = new Thread(new TCPDesktopServer());
desktopServerThread.start();
}
}

对上边的源代码做一些介绍:

指定Server监听的端口和服务器IP地址。

public static final String SERVERIP = "127.0.0.1";

public static final int SERVERPORT = 1818;

应用之前所指定的IP和Port创建一个ServerSocket对象。

ServerSocket serverSocket = new ServerSocket(SERVERPORT);

用于侦听和捕捉通过Socket连接的客户端。

Socket client = serverSocket.accept();

应用Socket创建BufferedReader对象,用于接收Socket Stream中的数据。

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

(二)客户端

main.java

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class main extends Activity implements OnClickListener{
/** Called when the activity is first created. */
//定义声明需要用到的UI元素
private EditText edtmsgcontent;
private Button btnSend;
private String ip="169.254.191.14";
private int port=1818;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
InitView();
}
private void InitView()
{
//显示主界面
setContentView(R.layout.main);
//通过id获取ui元素对象
edtmsgcontent=(EditText)findViewById(R.id.msgcontent);
btnSend=(Button)findViewById(R.id.btnsend);
//为btnsend设置点击事件
btnSend.setOnClickListener(this);
}

public void onClick(View bt)
{
try
{
String msg=edtmsgcontent.getText().toString();
if(!TextUtils.isEmpty(msg))
SendMsg(ip,port,msg);
else
{
Toast.makeText(this,"请先输入要发送的内容", Toast.LENGTH_LONG);
edtmsgcontent.requestFocus();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void SendMsg(String ip,int port,String msg) throws UnknownHostException, IOException
{
try
{
Socket socket=null;
socket=new Socket(ip,port);
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write(msg);
writer.flush();
writer.close();
socket.close();
}
catch(UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}

对上边的源代码做一些介绍:

应用Server的IP和端口建立Socket对象。

Socket socket = new Socket(ip, port);

根据已经建立的Socket来创建PrintWriter,将信息通过这个对象来发送给Server,其中包含了三个部分:

OutputStreamWriter

BufferedWriter

PrintWriter

PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);

 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.socket.client"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".main"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="7"></uses-sdk>
</manifest>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText android:text="EditText" android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/msgcontent"></EditText>
<Button android:layout_height="wrap_content" android:text="@string/Send" android:layout_width="fill_parent" android:id="@+id/btnsend"></Button>
</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Socket Client!</string>
<string name="app_name">Socket</string>
<string name="Send">发送</string>
</resources>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: