导航:首页 > 操作系统 > androidsocket传输文件

androidsocket传输文件

发布时间:2022-07-18 13:10:03

‘壹’ android如何通过socket上传视频或者音频先谢过啦

这个实验我是用两台pc做的实验,没有用真机,用的是emule,总体效果感觉可以
大致的思路是这样的
socket的通信分两种一种是 tcp另一种是udp,这个之间的通信方式我就不多说了,
主要的重点是权限的android.premisson,INTERNET

tcp
new Socket();
......

udp
new DatagramSocket();
......

‘贰’ 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报异常FileNotFoundException! 学习android开发编写SOCKET客户端,用来发送文件

FileNotFoundException:/f:/words.txt

看清楚异常的提示,它是报的文件“/f:/words.txt”没有找到,你用的是windows下的文件目录表示方法,可是android是基于linux平台的,它会到根目录“/”下找“f:”这个目录,这肯定找不到了。

解决方法:
1、将words.txt 放到项目的asserts目录下,然后
InputStream inputStream = SocketClientActivity.this.getAssets().open("words.txt");
2、将words.txt 放到SD卡里,然后
InputStream inputStream = new FileInputStream("/sdcard/words.txt");
3、也可以将你的文件放在你的工程默认路径下,然后再读:
FileInputStream fis = context.openFileInput("words.txt");

‘肆’ 在Android端使用socket传输图片到java服务器,求源代码

/**
*思想:
1.直接将所有数据安装字节数组发送
2.对象序列化方式
*/

/**
*thread方式
*
*@authorAdministrator
*/
{
privatestaticfinalintFINISH=0;
privateButtonsend=null;
privateTextViewinfo=null;
privateHandlermyHandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
caseFINISH:
Stringresult=msg.obj.toString();//取出数据
if("true".equals(result)){
TestSocketActivity4.this.info.setText("操作成功!");
}else{
TestSocketActivity4.this.info.setText("操作失败!");
}
break;
}
}
};


@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test_sokect_activity4);
//StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()
//.detectDiskReads().detectDiskWrites().detectNetwork()
//.penaltyLog().build());
//StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()
//.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
//.penaltyLog().penaltyDeath().build());

this.send=(Button)super.findViewById(R.id.send);
this.info=(TextView)super.findViewById(R.id.info);
this.send.setOnClickListener(newSendOnClickListener());
}

{
@Override
publicvoidonClick(Viewv){
try{
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
//1:
Socketclient=newSocket("192.168.1.165",9898);
//2:
ObjectOutputStreamoos=newObjectOutputStream(
client.getOutputStream());
//3:
UploadFilemyFile=SendOnClickListener.this
.getUploadFile();
//4:
oos.writeObject(myFile);//写文件对象
//oos.writeObject(null);//避免EOFException
oos.close();


BufferedReaderbuf=newBufferedReader(
newInputStreamReader(client
.getInputStream()));//读取返回的数据
Stringstr=buf.readLine();//读取数据
Messagemsg=TestSocketActivity4.this.myHandler
.obtainMessage(FINISH,str);
TestSocketActivity4.this.myHandler.sendMessage(msg);
buf.close();
client.close();
}catch(Exceptione){
Log.i("UploadFile",e.getMessage());
}
}
}).start();
}catch(Exceptione){
e.printStackTrace();
}
}

()throwsException{//包装了传送数据
UploadFilemyFile=newUploadFile();
myFile.setTitle("tangcco安卓之Socket的通信");//设置标题
myFile.setMimeType("image/png");//图片的类型
Filefile=newFile(Environment.getExternalStorageDirectory()
.toString()
+File.separator
+"Pictures"
+File.separator
+"b.png");
InputStreaminput=null;
try{
input=newFileInputStream(file);//从文件中读取
ByteArrayOutputStreambos=newByteArrayOutputStream();
bytedata[]=newbyte[1024];
intlen=0;
while((len=input.read(data))!=-1){
bos.write(data,0,len);
}
myFile.setContentData(bos.toByteArray());
myFile.setContentLength(file.length());
myFile.setExt("png");
}catch(Exceptione){
throwe;
}finally{
input.close();
}
returnmyFile;
}
}

}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;

publicStringgetTitle(){
returntitle;
}

publicvoidsetTitle(Stringtitle){
this.title=title;
}

publicbyte[]getContentData(){
returncontentData;
}

publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}

publicStringgetMimeType(){
returnmimeType;
}

publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}

publiclonggetContentLength(){
returncontentLength;
}

publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}

publicStringgetExt(){
returnext;
}

publicvoidsetExt(Stringext){
this.ext=ext;
}

}

下边是服务端

publicclassMain4{
publicstaticvoidmain(String[]args)throwsException{
ServerSocketserver=newServerSocket(9898);//服务器端端口
System.out.println("服务启动........................");
booleanflag=true;//定义标记,可以一直死循环
while(flag){//通过标记判断循环
newThread(newServerThreadUtil(server.accept())).start();//启动线程
}
server.close();//关闭服务器
}
}


{
="D:"+File.separator+"myfile"
+File.separator;//目录路径
privateSocketclient=null;
privateUploadFileupload=null;

publicServerThreadUtil(Socketclient){
this.client=client;
System.out.println("新的客户端连接...");
}

@Override
publicvoidrun(){
try{
ObjectInputStreamois=newObjectInputStream(
client.getInputStream());//反序列化
this.upload=(UploadFile)ois.readObject();//读取对象//UploadFile需要和客户端传递过来的包名类名相同,如果不同则会报异常
System.out.println("文件标题:"+this.upload.getTitle());
System.out.println("文件类型:"+this.upload.getMimeType());
System.out.println("文件大小:"+this.upload.getContentLength());

PrintStreamout=newPrintStream(this.client.getOutputStream());//BufferedWriter
out.print(this.saveFile());//返回响应
// BufferedWriterwriter=null;
// writer.write("");
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
this.client.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

privatebooleansaveFile()throwsException{//负责文件内容的保存
/**
*java.util.UUID.randomUUID():
*UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。UUID(Universally
*UniqueIdentifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,
*是由一个十六位的数字组成
*,表现出来的形式。由以下几部分的组合:当前日期和时间(UUID的第一个部分与时间有关,如果你在生成一个UUID之后,
*过几秒又生成一个UUID,
*则第一个部分不同,其余相同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得
*),UUID的唯一缺陷在于生成的结果串会比较长,字符串长度为36。
*
*UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。UUID(Universally
*UniqueIdentifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,
*是由一个十六位的数字组成,表现出来的形式
*/
Filefile=newFile(DIRPATH+UUID.randomUUID()+"."
+this.upload.getExt());
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();
}
OutputStreamoutput=null;
try{
output=newFileOutputStream(file);
output.write(this.upload.getContentData());
returntrue;
}catch(Exceptione){
throwe;
}finally{
output.close();
}
}
}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;

publicStringgetTitle(){
returntitle;
}

publicvoidsetTitle(Stringtitle){
this.title=title;
}

publicbyte[]getContentData(){
returncontentData;
}

publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}

publicStringgetMimeType(){
returnmimeType;
}

publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}

publiclonggetContentLength(){
returncontentLength;
}

publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}

publicStringgetExt(){
returnext;
}

publicvoidsetExt(Stringext){
this.ext=ext;
}

}

‘伍’ android socket写在Service中,为什么只能传输一次数据我这样写对吗求大神指导。。。

socket有两种连接方式:TCP与UDP,各有特点,
不知你用了哪种,TCP传输可靠,UDP不可靠会丢失包,
但UDP包有原路返回的特点,特别适合QQ这种的即时聊天工具。
你用TCP试试,不会丢失包的。

‘陆’ android socket 传输速度最大多少

服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。

‘柒’ 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
这个不就是接收的地方吗?在第一段代码中

‘捌’ 如何用socket实现android手机与手机之间的通信

有两种方案: 1、在PC机上建立服务器,手机与手机之间的通信通过服务器进行中转 2、一部手机作为服务器,另一部手机作为客户端接入该手机 一般是第一种方案 示例代码: 1、pc端: serverSocket=new ServerSocket(5648); //在5648端口进行侦听 Socket sk = serverSocket",5648);//连接socket 3、消息输入输出: pw=new PrintWriter(socket.getOutputStream()); //消息输出 pw.println("发送消息"); pw.flush(); br=new BufferedReader(new InputStreamReader(socket.getInputStream())); //消息接收 while((str=br.readLine())!=null){ //接收消息 }

‘玖’ android如何使用多线程及socket发送指令

1、后台服务是service,没有界面 2、主线程要给后台service传递一个对象可以使用通知也就是notifation 方法:在主线程生成一个通知管理器对象notifationmanager,把socket对象以通知消息的形式发送给后台service,详细的可以看看安卓巴士教程:http://www.apkbus.com/thread-463757-1-1.html

‘拾’ 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数据传输。

阅读全文

与androidsocket传输文件相关的资料

热点内容
好兴动app还款怎么登录不上去了 浏览:663
郑州云服务器托管 浏览:720
服务器地址跟踪 浏览:978
免费google云服务器 浏览:516
摘译和编译的英文 浏览:359
热泵压缩机选型 浏览:121
op手机微信加密如何解除 浏览:386
如何在王牌战争找到高爆率服务器 浏览:13
江浙小学语文辅导课用什么APP 浏览:99
新梦幻大陆服务器地址 浏览:241
网吧服务器怎么更换壁纸 浏览:530
linux命令方法 浏览:332
linux下载freetype 浏览:123
程序员入驻平台 浏览:327
程序员大战外挂 浏览:745
html实例教程pdf 浏览:157
linux命令开放所有权限 浏览:575
30岁能学会编程 浏览:737
小火箭的服务器是什么 浏览:967
cad查信息命令 浏览:402