㈠ android Socket通信開發,求詳細過程,附加註釋,謝謝
服務端往Socket的輸出流裡面寫東西,客戶端就可以通過Socket的輸入流讀取對應的內容。Socket與Socket之間是雙向連通的,所以客戶端也可以往對應的Socket輸出流裡面寫東西,然後服務端對應的Socket的輸入流就可以讀出對應的內容。
Socket類型為流套接字(streamsocket)和數據報套接字(datagramsocket)。
Socket基本實現原理
TCP與UDP
1基於TCP協議的Socket
伺服器端首先聲明一個ServerSocket對象並且指定埠號,然後調用Serversocket的accept()方法接收客戶端的數據。accept()方法在沒有數據進行接收的處於堵塞狀態。(Socketsocket=serversocket.accept()),一旦接收到數據,通過inputstream讀取接收的數據。
客戶端創建一個Socket對象,指定伺服器端的ip地址和埠號(Socketsocket=newSocket("172.168.10.108",8080);),通過inputstream讀取數據,獲取伺服器發出的數據(OutputStreamoutputstream=socket.getOutputStream()),最後將要發送的數據寫入到outputstream即可進行TCP協議的socket數據傳輸。
㈡ android如何與手機進行通信(Socket連接)
其實跟電腦差不多了,android里調用socket的方法,拿到socket後就可以發送數據並接收數據。
我最近正在做android方面的通信,真的想把完整的代碼都給你,可是沒辦法,公司機密。。
給你我的socket連接類吧。。。
package sean.socket;
///////////把MyType的一些方法替換成Writer的方法
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import sean.Sysout;
import sean.business.BusinessCenter;
import sean.business.LoginManager;
import sean.format.MyType;
import sean.io.Reader;
import sean.transfer.BytesBuffer;
import sean.transfer.DataCenter;
public class SocketThread implements Runnable {
String Server = "";
int Port = 0;
static Socket cs = null;
// Thread ioThread=null;
static boolean bool_SocketThread = false;
static OutputStream output = null;
public SocketThread(String server, int port) {
Server = server;
Port = port;
bool_SocketThread = true;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (bool_SocketThread) {
try {
// if (cs == null) {
DataCenter.setBool_Login(false);// 設置登錄失敗
Sysout.println("正在嘗試連接ClientSocket...", Sysout.TempOutDebug);
cs = new Socket(InetAddress.getByName(Server), Port);
if (cs != null) {
Sysout.println("ClientSocket連接成功!__" + cs,
Sysout.TempOutDebug);
cs.setKeepAlive(true);//讓socket保持活動狀態
InputStream input = cs.getInputStream();
output = cs.getOutputStream();
BusinessCenter.sendLoginData();
BytesBuffer bBuffer = new BytesBuffer();
byte[] Buffer = new byte[1024];
int ReadBytes = input.read(Buffer);
while (ReadBytes != -1) {
Sysout.println("已讀取" + ReadBytes + "個位元組到緩沖區",
Sysout.TempOutDebug);
byte[] b = new byte[ReadBytes];
b = MyType.BytesInsertToBytes(Buffer, b, 0);
Reader r = new Reader(b);
Sysout.println(r.toString() + "____ReadBytes=="
+ ReadBytes, Sysout.TempOutDebug);
bBuffer.InsertToBuffer(Buffer, ReadBytes);
ReadBytes = input.read(Buffer);
}
} else {
Sysout.printException("ClientSocket連接失敗!請確認網路正常且伺服器已開啟。");
}
// }
// 執行到這里說明inputstream.read()已中斷,說明socket已斷開連接
// cs=null;
LoginManager.setLoginValue(-1);// 業務中心登錄注銷,即登錄管理器注銷登錄
DataCenter.setBool_Login(false);// 數據中心登錄注銷
Sysout.printException(cs + "已斷開。");
Thread.sleep(2 * 1000);// 睡眠2秒後繼續循環
// try {
// // 判斷ClientSocket是否已斷開
// cs.sendUrgentData(0);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// Sysout.printException("ClientSocket已斷開,重新連接。"+e);
// cs.close();
// cs = null;
// }
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Sysout.printException("SocketThread.java====解析伺服器名稱發生異常!" + e);
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Sysout.printException("SocketThread發生IO異常,異常消息:" + e);
try {
if (cs != null) {
Sysout.println("准備關閉" + cs, Sysout.TempOutDebug);
cs.shutdownOutput();
cs.shutdownInput();
cs.close();
cs = null;
output = null;
LoginManager.setLoginValue(-1);// 業務中心登錄注銷,即登錄管理器注銷登錄
DataCenter.setBool_Login(false);// 數據中心登錄注銷
Sysout.println(cs + "已關閉。", Sysout.TempOutDebug);
}
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
Sysout.printException("SocketThread.java====線程睡眠異常!!"
+ e2);
// e2.printStackTrace();
}
String ExceptionInfos=e.toString();
if(ExceptionInfos.endsWith("Connection refused")){
stopSocketThread();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
Sysout.printException(cs + "關閉發生異常::" + e1);
// e1.printStackTrace();
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
Sysout.printException("SocketThread.java====線程睡眠異常!!"
+ e2);
// e2.printStackTrace();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// while(bool_SocketThread)
Sysout.println("SocketThread已停止。", Sysout.TempOutDebug);
}
public static Socket getSocket() {
return cs;
}
// public void setBool(boolean bool0) {
// bool_SocketThread = bool0;
// }
public static OutputStream getOutputStream() {
return output;
}
public static void stopSocketThread() {
try {
// 停止SocketThread線程,必須先把循環的標志bool_SocketThread置為false,否則可能繼續循環,重新建立socket連接
bool_SocketThread = false;
// 關閉socket
if (cs != null) {
cs.shutdownOutput();
cs.shutdownInput();
cs.close();
cs = null;
output = null;
Sysout.println("ClientSocket已被強制關閉。");
// LoginManager.setLoginValue(-1);// 業務中心登錄注銷,即登錄管理器注銷登錄
// DataCenter.setBool_Login(false);// 數據中心登錄注銷
// byte[] lock=LoginActivity.getLock();
// synchronized(lock){
// lock.notify();
// }
}
} catch (IOException e) {
// TODO Auto-generated catch block
Sysout.printException("強制關閉" + cs + "發生異常::" + e);
// e.printStackTrace();
}
}
}
必須先在android里啟動一個服務,由服務去啟動這個socket線程,因為如果是UI去啟動的話,頁面會卡住。。。
㈢ android如何使用多線程及socket發送指令
1、後台服務是service,沒有界面 2、主線程要給後台service傳遞一個對象可以使用通知也就是notifation 方法:在主線程生成一個通知管理器對象notifationmanager,把socket對象以通知消息的形式發送給後台service,詳細的可以看看安卓巴士教程:http://www.apkbus.com/thread-463757-1-1.html
㈣ C#編寫的socket伺服器如何發數據給android手機
以下是android手機上發送文件名並且得到文件大小的代碼Java
code
//
向伺服器提出下載請求,返回下載文件的大小
private
long
request(String
fileName,
String
password)
throws
IOException
{
//
獲取socket的輸入流並包裝成DataInputStream
DataInputStream
in
=
new
DataInputStream(socket.getInputStream());
//
獲取socket的輸出流並包裝成PrintWriter
PrintWriter
out
=
new
PrintWriter(new
OutputStreamWriter(
socket.getOutputStream()));
//
生成下載請求字元串
String
requestString
=
fileName;//
+
@
+
password;
System.out.println(發出下載請求:+fileName);
out.println(requestString);
//
發出下載請求
out.flush();
return
in.readLong();
//
接收並返回下載文件長度}
以下是C#伺服器收到android發來的文件名,知道文件之後發送文件大小和文件的代碼C#
code
private
string
ReceiveFileName(){string
recvStr
=
;byte[]
recvBytes
=
new
byte[1024];int
bytes
=
m_socket.Receive(recvBytes,
recvBytes.Length,
0);
//從android客戶端接受信息recvStr
=
Encoding.ASCII.GetString(recvBytes,
0,
bytes);Console.WriteLine(文件名+recvStr);return
recvStr;//返迴文件名}
private
void
SendFile(){while
(m_IsStart){string
fileName
=
ReceiveFileName();if
(fileName
!=
){if
(File.Exists(m_FileDirect
+
1.jpg))//下載本地存在的一個文件{FileInfo
fi
=
new
FileInfo(m_FileDirect
+
1.jpg);byte[]
len
=
BitConverter.GetBytes(fi.Length);m_socket.Send(len);//發送文件的長度//發送文件try{m_socket.SendFile(m_FileDirect
+
1.jpg);}catch
(Exception
e){Console.WriteLine(出現錯誤
+
e.Message);}}}}}
------解決方案--------------------------------------------------------
Java
code//
獲取socket的輸入流並包裝成DataInputStream
這個不就是接收的地方嗎?在第一段代碼中
㈤ android客戶端作為伺服器區域網用Socket,在一個activity中監聽埠。其他activity發送數據。如何實現呢
1 最簡單也是最笨的辦法是啟動要發送數據的Activity,然後在這個Activtiy進行發送數據。
2 如果你不能接受這樣的話,發送廣播通知那個Activity發送數據。
3 另外,個人覺得,在後台發送數據的功能還是不要寫在Activity的好,可以用service或者線程來實現。
4 如果你決定了用某種方法,咱們在進一步討論
㈥ android socket 發送數據時 程序停止運行
一般flush後就算是一次發送了,你可以打個斷點看看是否執行完了,先發送一次,多等一下,看看伺服器能收到不能,能的話就沒問題,說明是網速或其他延遲的原因
㈦ android做客戶端socket如何讓點擊按鈕向伺服器發送信息
使用基於TCP協議的Socket
一個客戶端要發起一次通信,首先必須知道運行伺服器端的主機IP地址。然後由網路基礎設施利用目標地址,將客戶端發送的信息傳遞到正確的主機上,在Java中,地址可以由一個字元串來定義,這個字元串可以使數字型的地址(比如192.168.1.1),也可以是主機名(example.com)。
而在android 4.0 之後系統以後就禁止在主線程中進行網路訪問了,原因是:
主線程是負責UI的響應,如果在主線程進行網路訪問,超過5秒的話就會引發強制關閉,所以這種耗時的操作不能放在主線程里。放在子線程里,而子線程里是不能對主線程的UI進行改變的,因此就引出了Handler,主線程里定義Handler,子線程里使用。
以下是一個android socket客戶端的例子:
---------------------------------Java代碼---------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TCPSocketActivity extends Activity {
public static final String TAG = TCPSocketActivity.class.getSimpleName();
/* 伺服器地址 */
private String host_ip = null;
/* 伺服器埠 */
private int host_port = 0;
private Button btnConnect;
private Button btnSend;
private EditText editSend;
private EditText hostIP;
private EditText hostPort;
private Socket socket;
private PrintStream output;
private String buffer = "";
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_test);
context = this;
initView();
btnConnect.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
host_ip = hostIP.getText().toString();
host_port = Integer.parseInt(hostPort.getText().toString());
new Thread(new ConnectThread()).start();
}
});
btnSend.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new SendThread(editSend.getText().toString())).start();
}
});
}
private void toastText(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
public void handleException(Exception e, String prefix) {
e.printStackTrace();
toastText(prefix + e.toString());
}
public void initView() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnSend = (Button) findViewById(R.id.btnSend);
editSend = (EditText) findViewById(R.id.sendMsg);
hostIP = (EditText) findViewById(R.id.hostIP);
hostPort = (EditText) findViewById(R.id.hostPort);
}
private void closeSocket() {
try {
output.close();
socket.close();
} catch (IOException e) {
handleException(e, "close exception: ");
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (0x123 == msg.what) {
toastText("連接成功!");
}
}
};
/* 連接socket線程 */
public class ConnectThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
try {
if (null == socket || socket.isClosed()) {
socket = new Socket();
socket.connect(new InetSocketAddress(host_ip,host_port),5000);
output = new PrintStream(socket.getOutputStream(), true,
"utf-8");
}
msg.what = 0x123;
handler.sendMessage(msg);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*發送信息線程*/
public class SendThread implements Runnable {
String msg;
public SendThread(String msg) {
super();
this.msg = msg;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
output.print(msg);
} catch (Exception e) {
e.printStackTrace();
}
closeSocket();
}
}
public class SocketThread implements Runnable {
public String txt1;
public SocketThread(String txt1) {
super();
this.txt1 = txt1;
}
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
try {
/* 連接伺服器 並設置連接超時為5秒 */
if (socket.isClosed() || null == socket) {
socket = new Socket();
socket.connect(new InetSocketAddress(host_ip,host_port),5000);
}
// 獲取輸入輸出流
PrintStream ou = new PrintStream(socket.getOutputStream(),
true, "UTF-8");
BufferedReader bff = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// 讀取發來伺服器信息
String line = null;
buffer = "";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}
// 向伺服器發送信息
ou.print(txt1);
ou.flush();
// 關閉各種輸入輸出流
bff.close();
ou.close();
socket.close();
msg.what = 0x123;
handler.sendMessage(msg);
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
}
}
-----------------------------布局文件activity_socket_test.xml--------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="vertical" >
<EditText
android:id="@+id/hostIP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="伺服器ip"
android:singleLine="true"
android:inputType="text" />
<EditText
android:id="@+id/hostPort"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="埠"
android:singleLine="true"
android:inputType="number" />
<Button
android:id="@+id/btnConnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:background="@drawable/style_btn_shape"
android:layout_margin="5dip"
android:text="@string/connect"
android:textColor="@color/white" />
<EditText
android:id="@+id/sendMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="需要發送的內容"
android:inputType="text" />
<Button
android:id="@+id/btnSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:background="@drawable/style_btn_shape"
android:layout_gravity="center_vertical|center_horizontal"
android:text="@string/send"
android:textColor="@color/white" />
</LinearLayout>
-------------------------樣式文件style_btn_shape.xml----------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充的顏色 -->
<solid android:color="#0465b2" />
<!-- 設置按鈕的四個角為弧形 -->
<!-- android:radius 弧形的半徑 -->
<corners android:radius="15dip" />
<!-- padding:Button裡面的文字與Button邊界的間隔 -->
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp"
/>
</shape>
------------------------------END---------------------------------------
㈧ android socket有幾種方法
/***第一種:客戶端Socket通過構造方法連接伺服器***/
//客戶端Socket可以通過指定IP地址或域名兩種方式來連接伺服器端,實際最終都是通過IP地址來連接伺服器
//新建一個Socket,指定其IP地址及埠號
Socket socket = new Socket("192.168.0.7",80);
/***Socket 客戶端 一些常用設置***/
//客戶端socket在接收數據時,有兩種超時:1.連接伺服器超時,即連接超時;2.連接伺服器成功後,接收伺服器數據超時,即接收超時
//*設置socket 讀取數據流的超時時間
socket.setSoTimeout(5000);
//發送數據包,默認為false,即客戶端發送數據採用Nagle演算法;
//但是對於實時交互性高的程序,建議其改為true,即關閉Nagle演算法,客戶端每發送一次數據,無論數據包大小都會將這些數據發送出去
socket.setTcpNoDelay(true);
//設置客戶端socket關閉時,close()方法起作用時延遲1分鍾關閉,如果1分鍾內盡量將未發送的數據包發送出去
socket.setSoLinger(true, 60);
//設置輸出流的發送緩沖區大小,默認是8KB,即8096位元組
socket.setSendBufferSize(8096);
//設置輸入流的接收緩沖區大小,默認是8KB,即8096位元組
socket.setReceiveBufferSize(8096);
//作用:每隔一段時間檢查伺服器是否處於活動狀態,如果伺服器端長時間沒響應,自動關閉客戶端socket
//防止伺服器端無效時,客戶端長時間處於連接狀態
socket.setKeepAlive(true);
/*** Socket客戶端向伺服器端發送數據 ****/
//客戶端向伺服器端發送數據,獲取客戶端向伺服器端輸出流
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//代表可以立即向伺服器端發送單位元組數據
socket.setOOBInline(true);
//數據不經過輸出緩沖區,立即發送
socket.sendUrgentData(65);//"A"
//向伺服器端寫數據,寫入一個緩沖區
//註:此處字元串最後必須包含「\r\n\r\n」,告訴伺服器HTTP頭已經結束,可以處理數據,否則會造成下面的讀取數據出現阻塞
//在write()方法中可以定義規則,與後台匹配來識別相應的功能,例如登錄Login()方法,可以寫為write("Login|test,123 \r\n\r\n"),供後台識別;
bw.write("Login|test,123 \r\n\r\n");
//發送緩沖區中數據,必須有
bw.flush();
/*** Socket客戶端讀取伺服器端響應數據 ****/
//socket.isConnected代表是否連接成功過
if((socket.isConnected() == true) && (socket.isClosed() == false)){//判斷Socket是否處於連接狀態
//客戶端接收伺服器端的響應,讀取伺服器端向客戶端的輸入流
InputStream is = socket.getInputStream();
//緩沖區
byte[] buffer = new byte[is.available()];
//讀取緩沖區
is.read(buffer);
//轉換為字元串
String responseInfo = new String(buffer);
//日誌中輸出
Log.i("TEST", responseInfo);
} //關閉網路
socket.close();
/***第二種:通過connect方法連接伺服器***/
Socket socket_other = new Socket();
//使用默認的連接超時
socket_other.connect(new InetSocketAddress("192.168.0.7",80));
//連接超時2s
socket_other.connect(new InetSocketAddress("192.168.0.7",80),2000);
//關閉socket
socket_other.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
㈨ 如何用socket實現android手機與手機之間的通信
有兩種方案:
1、在PC機上建立伺服器,手機與手機之間的通信通過伺服器進行中轉
2、一部手機作為伺服器,另一部手機作為客戶端接入該手機
一般用第一種方案,示例代碼如下:
1、pc端:
serverSocket=new ServerSocket(5648); //在5648埠進行偵聽
Socket sk = serverSocket.accept();//如果有接入,則創建對應的socket;
2、手機端:
socket=new Socket("tobacco5648.xicp.net",5648);//連接socket
3、消息輸入輸出:
pw=new PrintWriter(socket.getOutputStream()); //消息輸出
pw.println("發送消息");
pw.flush();
br=new BufferedReader(new InputStreamReader(socket.getInputStream())); //消息接收
while((str=br.readLine())!=null){
//接收消息
}