Android和PC端通過局域網(wǎng)文件同步用代碼怎么實現(xiàn)
局域網(wǎng)通常是分布在一個有限地理范圍內(nèi)的網(wǎng)絡(luò)系統(tǒng),一般所涉及的地理范圍只有幾公里。局域網(wǎng)專用性非常強,具有比較穩(wěn)定和規(guī)范的拓?fù)浣Y(jié)構(gòu)。這篇文章主要為大家詳細(xì)介紹了Android和PC端通過局域網(wǎng)文件同步的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
具體實現(xiàn)代碼如下
public class FileOptions {
public String name;
public String path;
public long size;
}
//Activity
public class MainActivity extends Activity {
private TextView tvMsg;
private EditText logShow, filePath;
private Handler handler;
private SocketManager socketManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
tvMsg = (TextView)findViewById(R.id. tvMsg);
logShow = (EditText)findViewById(R.id. log_show);
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg. what){
case 0:
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss" );
logShow.append( "\n[" + format.format(new Date()) + "]" + msg.obj .toString());
break;
case 1:
tvMsg.setText( "請在PC端輸入IP:" + GetIpAddress() + " 端口:" + msg.obj .toString());
break;
case 2:
Toast. makeText(getApplicationContext(), msg.obj.toString(), Toast. LENGTH_SHORT).show();
break;
}
}
};
socketManager = new SocketManager( handler);
}
@Override
protected void onDestroy() {
super.onDestroy();
System. exit(0);
}
public String GetIpAddress() {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE );
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int i = wifiInfo.getIpAddress();
return (i & 0xFF) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF)+ "." +
((i >> 24 ) & 0xFF );
}
}
//socket管理
public class SocketManager {
private static final String FILE_PATH= "/glass";
private static final String TAG = "SocketManager";
private ServerSocket server;
private Handler handler = null;
private List fileList;
public SocketManager(Handler handler) {
this. handler = handler;
int port = 9999;
while (port > 9000) {
try {
server = new ServerSocket(port);
break;
} catch (Exception e) {
port--;
}
}
SendMessage(1, port);
Thread receiveFileThread = new Thread( new Runnable() {
@Override
public void run() {
while ( true) { // 接收文件
ReceiveFile();
}
}
});
receiveFileThread.start();
}
void SendMessage( int what, Object obj) {
if ( handler != null) {
Message. obtain( handler, what, obj).sendToTarget();
}
}
// 接收文件
void ReceiveFile() {
Socket socketPC= null;
try {
GetAllFiles();
socketPC = server.accept();
InetAddress netAddr = socketPC.getInetAddress();
String ipaddr = netAddr.getHostAddress();
Log. w( TAG, ipaddr);
OutputStream outputStream = socketPC.getOutputStream();
JSONArray jsonArr= new JSONArray();
for( int i=0;i< fileList.size();i++){
try {
JSONObject jsonObj= new JSONObject();
jsonObj.put( "name", fileList.get(i). name);
jsonObj.put( "path", fileList.get(i). path);
jsonObj.put( "size", fileList.get(i). size);
jsonArr.put(jsonObj);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String sendStr=jsonArr.toString();
byte[] sendBuf=sendStr.getBytes( "GB2312");
outputStream.write(sendBuf, 0, sendBuf. length);
outputStream.flush();
SendMessage(0, " 發(fā)送文件索引完成" );
outputStream.close();
socketPC.close();
for( int i=0;i< fileList.size();i++){
Socket fileSendSocket = server.accept();
File fsend= new File( fileList.get(i). path);
FileInputStream fis= new FileInputStream(fsend);
OutputStream fos = fileSendSocket.getOutputStream();
byte[] buf = new byte[1024];
while ( true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
fos.write(buf,0,read);
}
fos.flush();
SendMessage(0, fileList.get(i). name+ "--文件傳輸完成" );
fis.close();
fos.close();
fileSendSocket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SendFile(ArrayList fileName, ArrayList path,
String ipAddress, int port) {
try {
for ( int i = 0; i < fileName.size(); i++) {
Socket name = new Socket(ipAddress, port);
OutputStream outputName = name.getOutputStream();
OutputStreamWriter outputWriter = new OutputStreamWriter(
outputName);
BufferedWriter bwName = new BufferedWriter(outputWriter);
bwName.write(fileName.get(i));
bwName.close();
outputWriter.close();
outputName.close();
name.close();
SendMessage(0, "正在發(fā)送" + fileName.get(i));
Socket data = new Socket(ipAddress, port);
OutputStream outputData = data.getOutputStream();
FileInputStream fileInput = new FileInputStream(path.get(i));
int size = -1;
byte[] buffer = new byte[1024];
while ((size = fileInput.read(buffer, 0, 1024)) != -1) {
outputData.write(buffer, 0, size);
}
outputData.close();
fileInput.close();
data.close();
SendMessage(0, fileName.get(i) + " 發(fā)送完成" );
}
SendMessage(0, "所有文件發(fā)送完成" );
} catch (Exception e) {
SendMessage(0, "發(fā)送錯誤:\n" + e.getMessage());
}
}
//待優(yōu)化
private void GetAllFiles(){
fileList= new ArrayList();
File rootPath= new File(Environment.getExternalStorageDirectory().getPath()+ FILE_PATH);
File[] files = rootPath.listFiles(); // 列出所有文件
for( int i=0;i
if(files[i].isFile()){
FileOptions fp= new FileOptions();
fp. name=files[i].getName();
fp. path=files[i].getPath();
fp. size=files[i].length();
fileList.add(fp);
}
}
}
}
PC端用VS2005寫的。用了Json格式數(shù)據(jù)進(jìn)行數(shù)據(jù)通信。主要用法為:在同一局域網(wǎng)內(nèi),打開PC端和Android端程序,按照Android端提示的IP地址及端口在PC端程序編輯框中正確輸入,點擊鏈接,即可將sd卡根目錄下的相關(guān)文件夾下的文件同步到PC端。
//PC端主要源碼
//數(shù)據(jù)傳輸線程
DWORD WINAPI RecvThread(LPVOID lpParameter)
{
SOCKET recvSocket = (SOCKET)lpParameter;
int ret = 0,strLen=0;
char recvBuffer[MAX_LEN],*pRecvAllData;
Json::Reader reader;
Json::Value jsonArr;
while ( true )
{
/*
*/
pRecvAllData=( char *)malloc(MAX_LEN);
while ((ret = recv(recvSocket, recvBuffer, MAX_LEN, 0))>0){
strLen+=ret;
pRecvAllData=( char *)realloc(pRecvAllData,strLen);
memcpy(pRecvAllData+strLen-ret,recvBuffer,ret);
};
if (!reader.parse(pRecvAllData, jsonArr)){
Sleep(1000);
continue ;
}
int jsonSize = jsonArr.size();
CString strItem;
fileList.RemoveAll();
for (int j = 0; j < jsonSize; ++j)
{
std::string name = jsonArr[j][ "name" ].asString();
std::string path = jsonArr[j][ "path" ].asString();
int size = jsonArr[j][ "size" ].asInt();
strItem.Format(TEXT( "%d" ), j+1);
pFileRecvDlg->m_fileListCtrl.InsertItem(j,strItem.GetBuffer(0));
pFileRecvDlg->m_fileListCtrl.SetItemText(j,0,strItem.GetBuffer(0));
strItem=name.c_str();
fileStr filest;
filest.name=name;
filest.size=size;
fileList.AddTail(filest);
pFileRecvDlg->m_fileListCtrl.SetItemText(j,1,strItem.GetBuffer(0));
}
free(pRecvAllData);
closesocket(recvSocket);
CRect rect;
pFileRecvDlg->GetClientRect(&rect);
pFileRecvDlg->ClientToScreen(rect);
if (!pProgressDlg->IsWindowVisible()){
pProgressDlg->ShowWindow(SW_SHOW);
}
pProgressDlg->SetWindowPos(NULL,rect.left+100,rect.top+100,0,0,SWP_NOSIZE);
pFileRecvDlg->GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(FALSE);
// 發(fā)送文件名
for (int i=0;i
SOCKET nameSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int ret = connect(nameSocket,( struct sockaddr*)&ServerAddr, sizeof (ServerAddr));
if ( ret == SOCKET_ERROR ){
AfxMessageBox(_T( "connect 失敗 "));
} else {
}
FILE *fp;
int tempCount=0;
fileStr flst=fileList.GetAt(fileList.FindIndex(i));
fopen_s(&fp,flst.name.c_str(), "wb+" );
pProgressDlg->setFile(flst.name,flst.size);
while ((ret = recv(nameSocket, recvBuffer, MAX_LEN, 0))!=0){
fwrite(recvBuffer, sizeof (char ),ret,fp);
tempCount+=ret;
pProgressDlg->updateProgress(tempCount);
}
_fcloseall( );
closesocket(nameSocket);
}
pFileRecvDlg->GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(TRUE);
pProgressDlg->ShowWindow(SW_HIDE);
}
return 0;
}
//連接按鈕的響應(yīng)函數(shù)
void CGlassFileRecvDlg::OnBnClickedButtonConnect()
{
// TODO: 在此添加控件通知處理程序代碼
if (UpdateData()){
BYTE nField0,nField1,nField2,nField3;
m_IpAddrCtrl.GetAddress(nField0,nField1,nField2,nField3);
WSADATA Ws;
SOCKET CientSocket;
int Ret = 0;
int AddrLen = 0;
HANDLE hThread = NULL;
char SendBuffer[MAX_PATH];
//Init Windows Socket
if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
{
return ;
}
//Create Socket
CientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( CientSocket == INVALID_SOCKET )
{
MessageBox(_T( "socket 創(chuàng)建失敗 " ));
return ;
}
char strAddr[50],tempStr[10];
memset(strAddr,0, sizeof (strAddr));
memset(tempStr,0, sizeof (tempStr));
itoa(nField0,tempStr,10);
strcat(strAddr,tempStr);
strcat(strAddr, "." );
itoa(nField1,tempStr,10);
strcat(strAddr,tempStr);
strcat(strAddr, "." );
itoa(nField2,tempStr,10);
strcat(strAddr,tempStr);
strcat(strAddr, "." );
itoa(nField3,tempStr,10);
strcat(strAddr,tempStr);
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = inet_addr(strAddr);
ServerAddr.sin_port = htons(m_port);
memset(ServerAddr.sin_zero, 0x00, 8);
Ret = connect(CientSocket,( struct sockaddr*)&ServerAddr, sizeof (ServerAddr));
if ( Ret == SOCKET_ERROR ){
MessageBox(_T( "connect 失敗 "));
return ;
} else {
HANDLE hThread = CreateThread(NULL, 0, RecvThread, (LPVOID)CientSocket, 0, NULL);
if ( hThread == NULL ){
MessageBox(_T( " 創(chuàng)建線程失敗 "));
return ;
}
CloseHandle(hThread);
}
}
}
補充:局域網(wǎng)、校園網(wǎng)安全維護(hù)方法
校園網(wǎng)絡(luò)分為內(nèi)網(wǎng)和外網(wǎng),就是說他們可以上學(xué)校的內(nèi)網(wǎng)也可以同時上互聯(lián)網(wǎng),大學(xué)的學(xué)生平時要玩游戲購物,學(xué)校本身有自己的服務(wù)器需要維護(hù);
在大環(huán)境下,首先在校園網(wǎng)之間及其互聯(lián)網(wǎng)接入處,需要設(shè)置防火墻設(shè)備,防止外部攻擊,并且要經(jīng)常更新抵御外來攻擊;
由于要保護(hù)校園網(wǎng)所有用戶的安全,我們要安全加固,除了防火墻還要增加如ips,ids等防病毒入侵檢測設(shè)備對外部數(shù)據(jù)進(jìn)行分析檢測,確保校園網(wǎng)的安全;
外面做好防護(hù)措施,內(nèi)部同樣要做好防護(hù)措施,因為有的學(xué)生電腦可能帶回家或者在外面感染,所以內(nèi)部核心交換機上要設(shè)置vlan隔離,旁掛安全設(shè)備對端口進(jìn)行檢測防護(hù);
內(nèi)網(wǎng)可能有ddos攻擊或者arp病毒等傳播,所以我們要對服務(wù)器或者電腦安裝殺毒軟件,特別是學(xué)校服務(wù)器系統(tǒng)等,安全正版安全軟件,保護(hù)重要電腦的安全;
對服務(wù)器本身我們要安全server版系統(tǒng),經(jīng)常修復(fù)漏洞及更新安全軟件,普通電腦一般都是撥號上網(wǎng),如果有異常上層設(shè)備監(jiān)測一般不影響其他電腦。做好安全防范措施,未雨綢繆。
Android和PC端通過局域網(wǎng)文件同步用代碼怎么實現(xiàn)相關(guān)文章:
1.同一無線局域網(wǎng)怎么用安卓設(shè)備訪問pc共享文件
2.沒有網(wǎng)怎么用局域網(wǎng)進(jìn)行手機電腦文件傳輸