最近有个移动端向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();
}
}
}