Windows 與移動設備socket通訊

最近有個移動端向Windows PC端發文件,考慮Socket 方案實現.

現記錄代碼如下:

Windows 代碼, 通過 MFC 框架實現 : Win32 Socket

void printHostIP()
{
char host[255];
if(gethostname(host,sizeof(host))==SOCKET_ERROR)
{
printf("無法獲取主機名\n");
}
else
{
printf("hostname:%s\n", host);
}

struct hostent *p=gethostbyname(host);

if(p==0)

{

printf("無法獲取計算機主機名及IP\n");

}

else

{

//本機IP:利用循環,輸出本機所有IP

for(int i=0;p->h_addr_list[i]!=0;i++)

{

struct in_addr in;

memcpy(&in,p->h_addr_list[i],sizeof(struct in_addr));

printf("第%d塊網卡ip:%s\n", i + 1, inet_ntoa(in));

}

}

}

void StartFileServer()

{

WSADATA data;

int m;

WORD w=MAKEWORD(2,0);

::WSAStartup(w,&data);

printHostIP();

SOCKET s,s1;

s=::socket(AF_INET,SOCK_STREAM,0);

sockaddr_in addr2,addr;

char text[1024]={0};

int n=sizeof(addr2);

addr.sin_family=AF_INET;

addr.sin_port=htons(7500);

addr.sin_addr.S_un.S_addr=INADDR_ANY;

::bind(s,(sockaddr *)&addr,sizeof(addr));

::listen(s,5);

printf("服務器已經啟動\r\n");

s1=::accept(s,(sockaddr*)&addr2,&n);

if(s1!=NULL){

printf("%s已經連接上\r\n",inet_ntoa(addr2.sin_addr));

CFile file1(TEXT("c:\\YongmingCache\\abc.jpg"),CFile::modeCreate|CFile::modeReadWrite);

if(file1!=NULL){

do{

m=::recv(s1,text,1024,0);

if (m > 0) {

file1.Write(text,m);

printf("寫入(%d)個數據\r\n", m);

} else {

printf("寫完了\r\n");

}

}while(m > 0);

}

file1.Flush();

file1.Close();

printf("傳輸完畢!");

}

::closesocket(s);

::closesocket(s1);

::WSACleanup();

printf("服務器退出\n");

}

iOS 代碼:

////  ViewController.m//  testSocket////  Created by Yongming on 2017/9/16.//  Copyright ? 2017年 Yongming. All rights reserved.//

#import "ViewController.h"

#import "GCDAsyncSocket.h"

@interface ViewController (){

GCDAsyncSocket* _socket;

dispatch_queue_t _socketQueue;

}

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

_socketQueue = dispatch_queue_create("socket_queue", NULL);

_socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:_socketQueue];

}

- (IBAction)onSendHandler:(id)sender {

NSError* error = NULL;

[_socket connectToHost:@"172.16.117.141" onPort:7500 error:&error];

if (error) {

NSLog(@"connect to host failed:%@", error.localizedDescription);

} else {

UIImage* image = [UIImage imageNamed:@"abc.jpg"];

NSData* imageData = UIImageJPEGRepresentation(image, 1);

[_socket writeData:imageData withTimeout:3000 tag:10];

}

}

#pragma mark - GCDAsyncSocketDelegate

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port

{

NSLog(@"didConnectToHost:%@:%d", host, port);

}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

NSLog(@"didReadData:%@,tag:%d", data ,(int)tag);

}

- (void) socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag

{

NSLog(@"didWriteDataWithTag:%d", (int)tag);

}

@end



安卓代碼如下:

packagecom.example.yongming.testviewpager;

importandroid.graphics.Bitmap;

importandroid.graphics.BitmapFactory;

importandroid.util.Log;

importjava.io.ByteArrayOutputStream;

importjava.io.DataOutputStream;

importjava.io.File;

importjava.io.FileInputStream;

importjava.net.InetSocketAddress;

importjava.net.Socket;

/**

* Created by Yongming on 2017/9/16.

*/

public classSocketHelper {

public static byte[]Bitmap2Bytes(Bitmap bm){

ByteArrayOutputStream baos =newByteArrayOutputStream();

bm.compress(Bitmap.CompressFormat.PNG,100,baos);

returnbaos.toByteArray();

}

public static voidStartConnect(Bitmap  bitmap)

{

String ip ="172.16.117.133";

intport =7500;

intlength =0;

byte[] sendByte =null;

Socket socket =null;

DataOutputStream dout =null;

FileInputStream fin =null;

try{

//Bitmap  bitmap = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.a);

byte[] pbytes =Bitmap2Bytes(bitmap);

if(pbytes.length==0)

return;

try{

socket =newSocket();

socket.connect(newInetSocketAddress(ip,port),3*1000);

dout =newDataOutputStream(socket.getOutputStream());

inttotallength = pbytes.length;

intperlength =1024;

intoffset =0;

while(offset < totallength){

dout.write(pbytes,offset,perlength);

dout.flush();

if((totallength - offset) > perlength) {

offset += perlength;

}else{

offset = totallength - offset;

}

Log.i("ym","write-total:"+ totallength +",per:"+ perlength +",offset:"+offset);

}

}catch(Exception e) {

Log.i("ym","error"+ e.getMessage());

}finally{

if(dout !=null)

dout.close();

if(fin !=null)

fin.close();

if(socket !=null)

socket.close();

}

}catch(Exception e) {
e.printStackTrace();
}
}
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,841評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,180評論 4 61
  • 自動引用計數 看完了 Objective-C 高級編程 第一章,不得不吐槽,翻譯這本書的作者的 English L...
    MoonBall閱讀 803評論 0 2
  • 我多想 走近你 依偎你溫暖的懷抱 親吻你如蘭的氣息 不,這些都不重要 我甚至愿意 做你近旁的一枚石子 當做快樂被拾...
    慕容蘭馨閱讀 338評論 9 7
  • 早起: 晨間日記: 喝水+中藥+早餐 工作繁碎小事 練字: 記賬:支出18 看書:千年一嘆173---186 英語...
    理想幾塊錢一斤閱讀 213評論 1 1