关于linux与android传输代码tcp -传文件
感谢原作者
Android(客户端)与Linux(服务器端)进行TCP数据通信__Programmer_的博客-CSDN博客_linux+安卓apptcp图传
原作者提供了linux与android 通过tcp连接 的代码
经过尝试,遇到一些bug,但最终解决,感谢作者的源代码!
本文主要将提取出传输部分,并改造成可以传输文件的代码
源代码(传输msg版)
默认是服务器先启动监听,然后客户端运行,建立连接,然后客户端发什么信息,服务端接受到会显示出来,并且重新发送给客户端。已经内置到自己的应用中,很成功。
服务端
采用的是8080端口
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#define PORT 8080 //服务器端监听端口号
#define MAX_BUFFER 1024 //数据缓冲区最大值
int main()
{
struct sockaddr_in server_addr, client_addr;
int server_sockfd, client_sockfd;
int size, write_size;
char buffer[MAX_BUFFER];
if ((server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) //创建Socket
{
perror("Socket Created Failed!\n");
exit(1);
}
printf("Socket Create Success!\n");
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
bzero(&(server_addr.sin_zero), 8);
int opt = 1;
int res = setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); //设置地址复用
if (res < 0)
{
perror("Server reuse address failed!\n");
exit(1);
}
if (bind(server_sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) //绑定本地地址
{
perror("Socket Bind Failed!\n");
exit(1);
}
printf("Socket Bind Success!\n");
if (listen(server_sockfd, 5) == -1) //监听
{
perror("Listened Failed!\n");
exit(1);
}
printf("Listening ....\n");
socklen_t len = sizeof(client_addr);
printf("waiting connection...\n");
if ((client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_addr, &len)) == -1) //等待客户端连接
{
perror("Accepted Failed!\n");
exit(1);
}
printf("connection established!\n");
printf("waiting message...\n");
while (1)
{
memset(buffer, 0, sizeof(buffer)); //清空数据缓冲区
if ((size = read(client_sockfd, buffer, MAX_BUFFER)) == -1) //读取客户端的数据
{
perror("Recv Failed!\n");
exit(1);
}
if (size != 0)
{
buffer[size] = '\0';
printf("Recv msg from client: %s\n", buffer);
if ((write_size = write(client_sockfd, buffer, MAX_BUFFER)) > 0) //把收到的数据回发给客户端
{
printf("Sent msg to client successfully!\n");
}
}
}
close(client_sockfd); //关闭Socket
close(server_sockfd);
return 0;
}
编译出可执行文件
g++ con.cpp -o server
运行
./server
移动端
TcpClientConnector.java
package com.google.ar.core.examples.java.helloar;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class TcpClientConnector {
private static TcpClientConnector mTcpClientConnector;
private Socket mClient;
private ConnectListener mListener;
private Thread mConnectThread;
public interface ConnectListener {
void onReceiveData(String data);
}
public void setOnConnectListener(ConnectListener listener) {
this.mListener = listener;
}
public static TcpClientConnector getInstance() {
if (mTcpClientConnector == null)
mTcpClientConnector = new TcpClientConnector();
return mTcpClientConnector;
}
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 100:
if (mListener != null) {
mListener.onReceiveData(msg.getData().getString("data"));
}
break;
}
}
};
public void createConnect(final String mSerIP, final int mSerPort) {
if (mConnectThread == null) {
mConnectThread = new Thread(new Runnable() {
@Override
public void run() {
try {
connect(mSerIP, mSerPort);
} catch (IOException e) {
e.printStackTrace();
}
}
});
mConnectThread.start();
}
}
/**
* 与服务端进行连接
*
* @throws IOException
*/
private void connect(String mSerIP, int mSerPort) throws IOException {
if (mClient == null) {
mClient = new Socket(mSerIP, mSerPort);
}
InputStream inputStream = mClient.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
String data = new String(buffer, 0, len);
Message message = new Message();
message.what = 100;
Bundle bundle = new Bundle();
bundle.putString("data", data);
message.setData(bundle);
mHandler.sendMessage(message);
}
}
/**
* 发送数据
*
* @param data 需要发送的内容
*/
public void send(String data) throws IOException {
if(mClient!=null)
{
Log.d("socket",mClient.toString());
OutputStream outputStream = mClient.getOutputStream();
outputStream.write(data.getBytes());
}
}
/**
* 断开连接
*
* @throws IOException
*/
public void disconnect() throws IOException {
if (mClient != null) {
mClient.close();
mClient = null;
}
}
}
main_activity.java
// 连接
private TcpClientConnector connector;
....
@Override
protected void onCreate(Bundle savedInstanceState) {
....
// 创建 连接
// 尝试连接
connector = TcpClientConnector.getInstance(); //获取connector实例
if(true){
//连接Tcp服务器端
connector.createConnect("10.112.146.228",8080); //调试使用
connector.setOnConnectListener(new TcpClientConnector.ConnectListener() {
@Override
public void onReceiveData(String data) {
//Received Data,do somethings.
System.out.println(data);
}
});
}else{
try{ //断开与服务器的连接
connector.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
.....
}
把发送信息的函数,加到你想加的函数里。记得android7以后,tcp连接必须放在线程中
new Thread(new Runnable(){
@Override
public void run() {
try {
connector.send("hello world");
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
源代码(传输文件版)
需求:需要从服务器传输一个文件,到客户端,客户端接收到后,保存至手机中。