android之socket編程實例
注意點:注冊訪問的網絡權限;android中UI線程不能有訪問網絡的操作,否則會報android.os.NetworkOnMainThreadException的異常
<pre class="html" name="code" snippet_file_name="blog_20131128_1_9516181" code_snippet_id="86031"> <uses-permission
android:name="android.permission.INTERNET"/></pre>
客戶端
package com.android.xiong.simplesocket;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketTimeoutException;
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends Activity { Socket socket = null; String buffer = ""; TextView txt1; Button send; EditText ed1; String geted1; public Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0x11) { Bundle bundle = msg.getData(); txt1.append("server:"+bundle.getString("msg")+"\n"); } }
}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt1 = (TextView) findViewById(R.id.txt1); send = (Button) findViewById(R.id.send); ed1 = (EditText) findViewById(R.id.ed1); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { geted1 = ed1.getText().toString(); txt1.append("client:"+geted1+"\n"); //啟動線程 向服務器發送和接收信息 new MyThread(geted1).start(); } }); } class MyThread extends Thread { public String txt1; public MyThread(String str) { txt1 = str; } @Override public void run() { //定義消息 Message msg = new Message(); msg.what = 0x11; Bundle bundle = new Bundle(); bundle.clear(); try { //連接服務器 并設置連接超時為5秒 socket = new Socket(); socket.connect(new InetSocketAddress("1.1.9.30", 30000), 5000); //獲取輸入輸出流 OutputStream ou = socket.getOutputStream(); BufferedReader bff = new BufferedReader(new InputStreamReader( socket.getInputStream())); //讀取發來服務器信息 String line = null; buffer=""; while ((line = bff.readLine()) != null) { buffer = line + buffer; } //向服務器發送信息 ou.write("android 客戶端".getBytes("gbk")); ou.flush(); bundle.putString("msg", buffer.toString()); msg.setData(bundle); //發送消息 修改UI線程中的組件 myHandler.sendMessage(msg); //關閉各種輸入輸出流 bff.close(); ou.close(); socket.close(); } catch (SocketTimeoutException aa) { //連接超時 在UI界面顯示消息 bundle.putString("msg", "服務器連接失敗!請檢查網絡是否打開"); msg.setData(bundle); //發送消息 修改UI線程中的組件 myHandler.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }
}</pre>
<RelativeLayout xmlns:android="<EditText android:id="@+id/ed1" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="給服務器發送信息"/> <Button android:id="@+id/send" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/ed1" android:text="發送"/> <TextView android:id="@+id/txt1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/send"/>
</RelativeLayout></pre>
服務端
package com.android.net;import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List;
public class AndroidService {
public static void main(String[] args) throws IOException { ServerSocket serivce = new ServerSocket(30000); while (true) { //等待客戶端連接 Socket socket = serivce.accept(); new Thread(new AndroidRunable(socket)).start(); } }
}</pre>
package com.android.net;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.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket;
public class AndroidRunable implements Runnable {
Socket socket = null; public AndroidRunable(Socket socket) { this.socket = socket; } @Override public void run() { // 向android客戶端輸出hello worild String line = null; InputStream input; OutputStream output; String str = "hello world!"; try { //向客戶端發送信息 output = socket.getOutputStream(); input = socket.getInputStream(); BufferedReader bff = new BufferedReader( new InputStreamReader(input)); output.write(str.getBytes("gbk")); output.flush(); //半關閉socket socket.shutdownOutput(); //獲取客戶端的信息 while ((line = bff.readLine()) != null) { System.out.print(line); } //關閉輸入輸出流 output.close(); bff.close(); input.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }
}</pre>