安卓TCP通信版本2

PC做服務器,安卓做客戶端。

安卓獲取輸入框的內容并發送,然后等待接收服務器的消息

服務器先行開啟,接收到客戶端的數據,然后回復消息。

?

實現了對線程類的封裝,通過按鈕啟動線程發送并接收

服務器代碼(java版):

import java.io.*;
import java.net.*;/*
需求:定義端點接收數據并打印在控制臺服務端:
1.創建服務端serversocket對象并指定端口當不指定時,使用connect方法指定
2. 獲取連接過來的客戶端對象通過serversocket的accept方法等待,阻塞式,無連接一直等待
3.客戶端如果發過來數據,服務端使用對應連接的讀取流獲取發過來數據打印在服務臺
4,關閉服務端(可選)
*/class tcpServer
{public static void main(String[] args) throws IOException{//建立服務端socket服務,并監聽端口ServerSocket ss =new ServerSocket(30000);
// 采用循環不斷接受來自客戶端的請求while (true){//通過accept方法獲取鏈接過來的客戶端對象(s中有內容,端口,IP屬性)Socket s = ss.accept();/*接收手機數據*///IP:String ip =s.getInetAddress().getHostAddress();System.out.println(ip+"...連接成功" );//內容:獲取客戶端發送過來的數據,那么要使用客戶端對象sInputStream in = s.getInputStream();byte[] buf =new byte[1024];int len=in.read(buf);String content = new String(buf,0,len);System.out.println("內容:"+content );/*回發給手機數據*/OutputStream os = s.getOutputStream();os.write("歡迎回來學安卓,您收到了泡泡的祝福!\n".getBytes("utf-8"));//s.close();//關閉客戶端,服務器可以控制客戶//ss.close();//關閉服務端,可選操作
}
}
}
tcpServer.java

安卓代碼(安卓版):

后臺代碼:

package com.simpleclient;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.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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 {private EditText mEditText = null;  private TextView mTextView = null;  private Button mButton = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mButton = (Button)findViewById(R.id.mButton);  mEditText = (EditText)findViewById(R.id.mEditText);  mTextView = (TextView)findViewById(R.id.mTextView); mButton.setOnClickListener(new StartSocketListener());}//啟動按鈕監聽class StartSocketListener implements OnClickListener{@Overridepublic void onClick(View v) {new ServerThread().start();} }class ServerThread extends Thread{// TCP 協議
        @Overridepublic void run(){Socket socket=null;try{/* 指定Server的IP地址,此地址為局域網地址,如果是使用WIFI上網,則為PC機的WIFI IP地址 * 在ipconfig查看到的IP地址如下: * Ethernet adapter 無線網絡連接: * Connection-specific DNS Suffix  . : IP Address. . . . . . . . . . . . : 192.168.1.100 */  // 1建立連接到遠程服務器的Socketsocket = new Socket("192.168.1.108" , 30000);  //Log.d("TCP", "C: Connecting..."); //2向服務端發送數據  BufferedWriter bufwriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));// 把用戶輸入的內容發送給server  String lineWrite = mEditText.getText().toString(); Log.d("TCP", "C: Sending: '" + lineWrite + "'");bufwriter.write(lineWrite);//向服務端發送數據  
                bufwriter.newLine();  bufwriter.flush(); //3接收服務器信息   // 將Socket對應的輸入流包裝成BufferedReaderBufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));// 進行普通IO操作,得到服務器信息String line = br.readLine();mTextView.setText("讀取到自服務器的數據:" + line);// 關閉輸入流、socket
                br.close();//socket.close();
            }catch(UnknownHostException e) {  Log.e("TCP errror", "192.168.1.108 is unkown server!");  } catch(Exception e) {  e.printStackTrace();  } finally {  try {  socket.close();  } catch(Exception e) {  e.printStackTrace();  }  }  }}}
MainActivity.java

前臺代碼:

<?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">
<!-- 獲取輸入框信息并發送出去 --><EditTextandroid:id="@+id/mEditText"android:layout_width="fill_parent"android:layout_height="40dp"android:cursorVisible="false"android:editable="true" android:ems="10" ></EditText><TextViewandroid:id="@+id/mTextView"android:layout_width="fill_parent"android:layout_height="50dp"android:ems="10" ></TextView><Buttonandroid:id="@+id/mButton"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="TCP客戶端---發送" /></LinearLayout>
activity_main.xml

權限代碼:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.simpleclient"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="14"android:targetSdkVersion="19" /><uses-permission android:name="android.permission.INTERNET"/><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name=".MainActivity"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></manifest>
use_permisson

效果:

問題:亂碼問題還沒有解決掉~

轉載于:https://www.cnblogs.com/shuqingstudy/p/4964057.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/375381.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/375381.shtml
英文地址,請注明出處:http://en.pswp.cn/news/375381.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Win32ASM學習[5]: 數據對齊相關的偽指令(ALIGN、EVEN、ORG)

32 位的寄存器容量是 4 字節, 如果內存中的數據都按 4*n 字節對齊, 肯定會加快吞吐速度; 但事實并非如此, 不同大小的數據可能會讓寄存器別別扭扭地去處理, 從而降低了運行速度! 如果使用對齊, 就會浪費掉一些內存空間; 其實這是一個需要權衡 "速度" 與 "內存&…

常用Jquery前端操作

input只能輸入正整數 οnkeyup"this.valuethis.value.replace(/\D/g,)"if(!confirm("刪除后無法恢復&#xff0c;確認繼續&#xff1f;")){return false;}//判斷字符串里是否存在指定字符 if(str.indexOf("abc") ! -1){//表示存在}1.雙引號替換…

【Linux/Ubuntu學習 10】unbuntu 下 eclipse 中文亂碼的解決

wangddwdd-pc:~$ gedit /var/lib/locales/supported.d/local 添加&#xff1a; zh_CN.GBK GBKzh_CN.GB2312 GB2312 終端執行命令&#xff1a; sudo dpkg-reconfigure --force localesGenerating locales... en_AG.UTF-8... done en_AU.UTF-8... done en_BW.UTF-8... done …

Win32ASM學習[6]: PTR、OFFSET、ADDR、THIS

PTR: 指定要操作的數據尺寸 ------------------------------------------------------------------------------------------------------------------------------------------ .386 .model flat, stdcall include windows.inc include kernel32.inc include masm…

簡述WebService的使用(一)

環境&#xff1a; vs版本&#xff1a;vs2013 windows版本&#xff1a;win7 IIS版本&#xff1a;IIS7.0 &#xff08;如果覺得對您有用&#xff0c;請點擊右下角【推薦】一下&#xff0c;讓更多人看到&#xff0c;謝謝&#xff09; 配置環境&#xff1a; 主要針對于IIS 首先&…

【Java基礎】用LinkedList實現一個簡單棧的功能

棧的基本功能 棧的最基本功能是保障后進先出&#xff0c;然后在此基礎上可以對在棧中的對象進行彈入彈出&#xff0c;此外&#xff0c;在彈出時&#xff0c;如果棧為空&#xff0c;則會報錯&#xff0c;所以還需要提供獲取當前棧大小的方法。 構造存儲對象Student /*** Created…

Win32匯編學習[7]: 定義符號常量(=、EQU、TEXTEQU)

關于符號常量 的例子 .386 .model flat,stdcall include windows.inc include kernel32.inc include masm32.inc include debug.inc includelib kernel32.lib includelib masm32.lib includelib debug.lib .data n 1 ; 偽指令只能定義整數或整數表達式…

oracle 刪除表中重復記錄,并保留一條

1、查找表中多余的重復記錄&#xff0c;重復記錄是根據單個字段&#xff08;Id&#xff09;來判斷 select * from 表 where Id in (select Id from 表 group byId having count(Id) > 1) 2、刪除表中多余的重復記錄&#xff0c;重復記錄是根據單個字段&#xff08;Id&#x…

透過WinDBG的視角看String

摘要 : 最近在博客園里面看到有人在討論 C# String的一些特性. 大部分情況下是從CODING的角度來討論String. 本人覺得非常好奇, 在運行時態, String是如何與這些特性聯系上的. 本文將側重在通過WinDBG來觀察String在進程內的布局, 以此來解釋C# String的一些特性. 問題 C# Stri…

Win32ASM學習[8]: 進制轉換的庫函數

在 masm32.inc 中有這樣幾個函數的聲明: byt2bin_ex PROTO :BYTE, :DWORD wrd2bin_ex PROTO :WORD, :DWORD dw2bin_ex PROTO :DWORD, :DWORD dw2hex_ex PROTO :DWORD, :DWORD bin2byte_ex PROTO :DWORD -------------------------------------------------------------…

SOJ 2800_三角形

真的是O不是0【看了discuss才發現。。。。。一個大寫的蠢 【題意】多個黑白三角形組成的倒三角&#xff0c;求白三角形組成的最大倒三角的面積 【分析】由于問的是倒三角個數&#xff0c;所以只需看與行數奇偶性相同的白色倒三角形&#xff0c;設v[i][j]為以第i行第j列的倒三角…

ueditor富文本編輯器 修改框寬度和高度的方法

在使用ueditor的時候&#xff0c;用的textarea <textarea name"content" id"myEditor">這里寫這條規則的回復內容</textarea> 給它加style"width:300" 屬性的時候&#xff0c;發現不起作用。 正確的方法應該是&#xff1a; <scri…

Win32ASM學習[9]: 標志寄存器

TF(Trap Flag)——位8&#xff0c;跟蹤標志。置1 則開啟單步執行調試模式&#xff0c;置0 則關閉。在單步執行模式下&#xff0c;處理器在每條指令后產生一個調試異常&#xff0c;這樣在每條指令執行后都可以查看執行程序的狀態。如果程序用POPF、POPFD 或者ET 指令設置TF 標志…

TCP多進程并發服務端 Linux socket編程入門(2)

這里很簡單的使用了fork()函數&#xff0c;在執行了fork()以后的所有代碼都會由子進程和父進程同時執行。 他們同時擁有相同的資源&#xff08;兩份拷貝&#xff09;&#xff0c;所以在子進程執行的過程中&#xff0c;子進程需要先close掉listenfd&#xff08;監聽套接字&#…

ArcEngine 打開shape文件

IWorkspaceFactory wsf new ShapefileWorkspaceFactory(); IWorkspace pWorkspace wsf.Open(filePath, 0) ;//filePath為shapefile所在的文件夾 IFeatureWorkspace pFeatureWorkspace pWorkspace ; IFeatureClass pFeatureClass pFeatureWorkspace.OpenFeatureClass(&quo…

Win32ASM學習[10]:傳送指令

匯編指令的一般性要求: 1、兩個操作數的尺寸必須一致; 2、操作數不能同為內存. --------------------------------------------------------------------------------------------------------------- ;mov ;該指令不影響 EFlags ;指令格式: (其中的 r、m、i 分別表示: 寄存器、…

SQL Server 中關于 @@error 的一個小誤區

SQL Server 中關于 error 的一個小誤區 原文:SQL Server 中關于 error 的一個小誤區在SQL Server中&#xff0c;我常常會看到有些前輩這樣寫&#xff1a; if(error<>0)ROLLBACK TRANSACTION T elseCOMMIT TRANSACTION T 一開始&#xff0c;我看見別人這么寫&#xff0c;我…

Win32ASM學習[11]:邏輯運算

--------------------------------------------------------------------------------------------------------------------------- 一.邏輯與運算指令 AND 格式: AND OPRD1,OPRD2其中目的操作數OPRD1為任一通用寄存器或存儲器操作數.源操作數OPRD2為立即數、任一通用寄存器…

JavaScript消息框

1.警告框 function myTest(){alert("這里的內容會彈出");} 2.確認框 其返回的值是 true 或 false 。 function myTest(){confirm("這里的內容會彈出");} 3.提示框 prompt prompt(參數1&#xff0c;參數2)&#xff1a;其參數1 是顯示提示要輸入的信息&…

.Net 事務

在分布式應用程序中&#xff0c;不可避免地會經常使用到事務控制。事務有一個開頭和一個結尾&#xff0c;它們指定了事務的邊界&#xff0c;事務在其邊界之內可以跨越進程和計算機。事務邊界內的所有資源都參與同一個事務。要維護事務邊界內資源間的一致性&#xff0c;事務必須…