Android通過socket串連伺服器(PC)

來源:互聯網
上載者:User

Server端

package com.test;</p><p>import java.io.BufferedReader;<br />import java.io.BufferedWriter;<br />import java.io.File;<br />import java.io.FileOutputStream;<br />import java.io.InputStreamReader;<br />import java.io.OutputStreamWriter;<br />import java.io.PrintWriter;<br />import java.net.ServerSocket;<br />import java.net.Socket;</p><p>public class Server implements Runnable {<br />public static final String SERVERIP = "10.0.2.2";<br />public static final int SERVERPORT = 51706;</p><p>public void run() {<br />try {<br />System.out.println("S: Connecting...");</p><p>ServerSocket serverSocket = new ServerSocket(SERVERPORT);<br />while (true) {</p><p> //等待接受用戶端請求<br />Socket client = serverSocket.accept();</p><p>System.out.println("S: Receiving...");</p><p>try {</p><p> //接受用戶端資訊<br />BufferedReader in = new BufferedReader(<br />new InputStreamReader(client.getInputStream()));</p><p>Socket socket = null;</p><p> //發送訊息  <br /> PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);</p><p> //設定返回資訊<br /> out.println("my name is server");<br /> out.flush();</p><p> String str = in.readLine();<br /> File file = new File ("C://file//android.txt");<br /> FileOutputStream fops = new FileOutputStream(file);<br /> byte [] b = str.getBytes();;<br /> for ( int i = 0 ; i < b.length-1; i++ )<br /> {<br /> fops.write(b[i]);<br />System.out.println(b.toString());<br /> }</p><p>System.out.println("S: Received: '" + str + "'");</p><p>} catch (Exception e) {</p><p>System.out.println("S: Error");</p><p>e.printStackTrace();</p><p>} finally {</p><p>client.close();</p><p>System.out.println("S: Done.");</p><p>}</p><p>}</p><p>} catch (Exception e) {</p><p>System.out.println("S: Error");</p><p>e.printStackTrace();</p><p>}</p><p>}</p><p>public static void main(String [] args ) {</p><p>Thread desktopServerThread = new Thread(new Server());</p><p>desktopServerThread.start();</p><p>}<br />}

 

Client端

package com.lde;</p><p>import java.io.BufferedReader;<br />import java.io.BufferedWriter;<br />import java.io.InputStreamReader;<br />import java.io.OutputStreamWriter;<br />import java.io.PrintWriter;<br />import java.net.InetAddress;<br />import java.net.ServerSocket;<br />import java.net.Socket;</p><p>import android.app.Activity;<br />import android.os.Bundle;<br />import android.util.Log;<br />import android.view.View;<br />import android.view.View.OnClickListener;<br />import android.widget.Button;<br />import android.widget.EditText;<br />import android.widget.TextView;</p><p>public class Socket_Android extends Activity {</p><p>private TextView mTextView = null;<br />private EditText mEditText = null;<br />private TextView tx1 = null;</p><p>private Button mbutton = null;</p><p>/** Called when the activity is first created. */<br />@Override<br />public void onCreate(Bundle savedInstanceState) {<br />super.onCreate(savedInstanceState);<br />setContentView(R.layout.main);</p><p>mbutton = ( Button ) findViewById(R.id.Button01);<br />mEditText = ( EditText ) findViewById( R.string.EditText01);<br />mTextView = ( TextView ) findViewById ( R.string.TextView01);<br />tx1 = ( TextView ) findViewById ( R.id.tx);</p><p>mbutton.setOnClickListener(new OnClickListener() {<br />public void onClick(View v) {<br />setTitle("abcdefg");<br />Socket socket = null;<br />try {</p><p>// 指定Server的IP地址<br />InetAddress serverAddr = InetAddress.getByName("10.0.2.2");// TCPServer.SERVERIP</p><p>Log.d("TCP", "C: Connecting...");</p><p>// 應用Server的IP和連接埠建立Socket對象<br />socket = new Socket(serverAddr, 51706);<br />String message = "---Test_Socket_Android---";</p><p>Log.d("TCP", "C: Sending: '" + message + "'");</p><p>// 將資訊通過這個對象來發送給Server<br />PrintWriter out = new PrintWriter(new BufferedWriter(<br />new OutputStreamWriter(socket.getOutputStream())),<br />true);</p><p>//接受伺服器資訊<br /> BufferedReader in = new BufferedReader(<br /> new InputStreamReader(socket.getInputStream()));<br /> //得到伺服器資訊<br /> String msg = in.readLine();<br /> //在頁面上進行顯示<br /> tx1.setText(msg);</p><p>out.println(msg);<br />out.flush();</p><p>} catch (Exception e) {</p><p>Log.e("TCP", "S: Error", e);<br />} finally {<br /> try {<br />// ServerSocket serverSocket = new ServerSocket(51706);<br />// Socket client = serverSocket.accept();<br />// BufferedReader in = new BufferedReader(<br />// new InputStreamReader(client.getInputStream()));<br />//<br />// String str = in.readLine();<br />// tx1.setText("123");</p><p>// System.out.println("S: Received: '" + str + "'");<br />//<br />// System.out.println("S: Received: '" + str + "'");</p><p>socket.close();<br />} catch (Exception e) {<br />// TODO Auto-generated catch block<br />e.printStackTrace();<br />}<br />}<br />}<br />}</p><p>);<br />}<br />// public void a () throws IOException<br />// {<br />// //指定Server的IP地址<br />// InetAddress serverAddr =<br />// InetAddress.getByName("110.149");//TCPServer.SERVERIP<br />// Log.d("TCP", "C: Connecting...");<br />//<br />// //應用Server的IP和連接埠建立Socket對象<br />// Socket socket = new Socket(serverAddr, 51706);<br />// String message = "AndroidRes,Where is my Pig (Android)?";<br />// try {<br />//<br />// Log.d("TCP", "C: Sending: '" + message + "'");<br />//<br />// //將資訊通過這個對象來發送給Server<br />// PrintWriter out = new PrintWriter( new BufferedWriter( new<br />// OutputStreamWriter(socket.getOutputStream())),true);<br />//<br />// out.println(message);<br />// } catch(Exception e) {<br />//<br />// Log.e("TCP", "S: Error", e);<br />// } finally {<br />//<br />// socket.close();<br />// }<br />// }</p><p>}

 

R.java

 

/* AUTO-GENERATED FILE. DO NOT MODIFY.<br /> *<br /> * This class was automatically generated by the<br /> * aapt tool from the resource data it found. It<br /> * should not be modified by hand.<br /> */</p><p>package com.lde;</p><p>public final class R {<br /> public static final class attr {<br /> }<br /> public static final class drawable {<br /> public static final int icon=0x7f020000;<br /> }<br /> public static final class id {<br /> public static final int Button01=0x7f050000;<br /> public static final int tx=0x7f050001;<br /> }<br /> public static final class layout {<br /> public static final int main=0x7f030000;<br /> }<br /> public static final class string {<br /> public static final int Button01=0x7f040003;<br /> public static final int EditText01=0x7f040004;<br /> public static final int TextView01=0x7f040002;<br /> public static final int app_name=0x7f040001;<br /> public static final int hello=0x7f040000;<br /> }<br />}<br />

 

main.xml

 

<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:orientation="vertical"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"<br /> ><br /> <!--<br /><TextView<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text="@string/hello"<br /> /><br /> --><br /> <TextView<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text="@string/TextView01" /></p><p><EditText<br />android:layout_width="fill_parent"<br />android:layout_height="wrap_content"<br />android:text="@string/EditText01" /></p><p><Button<br />android:id="@+id/Button01"<br />android:layout_width="fill_parent"<br />android:layout_height="wrap_content"<br />android:text="@string/Button01" /><br /><TextView android:id="@+id/tx"<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"/><br /></LinearLayout><br />

 

string.xml

 

<?xml version="1.0" encoding="utf-8"?><br /><resources><br /> <string name="hello">Hello World, Socket_Android!</string><br /> <string name="app_name">Socket_Android</string><br /> <string name="TextView01">這裡顯示接受到伺服器發來的資訊</string><br /> <string name="Button01">測試連接</string><br /> <string name="EditText01">請輸入內容</string><br /></resources><br />

 

 

AndroidManifest.xml

 

<?xml version="1.0" encoding="utf-8"?><br /><manifest xmlns:android="http://schemas.android.com/apk/res/android"<br /> package="com.lde"<br /> android:versionCode="1"<br /> android:versionName="1.0"><br /> <uses-sdk android:minSdkVersion="5" /></p><p> <application android:icon="@drawable/icon" android:label="@string/app_name"><br /> <activity android:name=".Socket_Android"<br /> android:label="@string/app_name"><br /> <intent-filter><br /> <action android:name="android.intent.action.MAIN" /><br /> <category android:name="android.intent.category.LAUNCHER" /><br /> </intent-filter><br /> </activity><br /> </application><br /><!-- 一定要加入下面這句話 給它設定上許可權--><br /> <uses-permission android:name="android.permission.INTERNET" /><br /></manifest>

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.