㈠ 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){
//接收消息
}