发送和接受文件的程序

22 篇文章 0 订阅
21 篇文章 0 订阅

只要知道机器的IP地址 和端口号就可以通过下面的简单程序进行发送文件。

下面的程序可以运行在UNIX/Linux 和windows上。

后面会陆续更新各个语言的版本。

//发送文件

#ifdef __gnu_linux__
//linux special 
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdbool.h>
#define SOCKET int
#endif

#ifdef _WIN32
//win32 special 
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib, "Ws2_32.lib")
#define close closesocket
#define read(fd, buf, n) recv(fd, buf, n, 0)
#define write(fd, buf, n) send(fd, buf, n, 0)
#define socklen_t int
#endif

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

char __commbuff[4096];

void trim(char *s)
{
    char *start;
    char *end;
    int len = strlen(s);

    start = s;
    end = s + len - 1;

    while (1)
    {
        char c = *start;
        if (!isspace(c))
            break;

        start++;
        if (start > end)
        {
            s[0] = '\0';
            return;
        }
    }

    while (1)
    {
        char c = *end;
        if (!isspace(c))
            break;

        end--;
        if (start > end)
        {
            s[0] = '\0';
            return;
        }
    }

    memmove(s, start, end - start + 1);
    s[end - start + 1] = '\0';
}



void Init()
{
#ifdef _WIN32
    WORD wVersionRequested = MAKEWORD(2, 2);
    static WSADATA wsaData;
    WSAStartup(wVersionRequested, &wsaData);
#endif
}

void Clean()
{
#ifdef _WIN32
    WSACleanup();
#endif
}

SOCKET MakeTcpSocket(char *ip, short port)
{
    SOCKET sfd = socket(AF_INET, SOCK_STREAM, 0); 

    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr.s_addr = ip ? inet_addr(ip) : INADDR_ANY; 

    if (!ip)
    {
        int v = 1;
#ifdef _WIN32
        int rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&v, sizeof (v));
#if 0
        //
        v = 1;
        setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&v,sizeof (v));//使用KEEPALIVE
        v = 1;
        setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (const char *)&v, sizeof (v));//禁用NAGLE算法
        struct linger opv;
        opv.l_onoff = 1;
        opv.l_linger = 10;
        setsockopt(sfd, SOL_SOCKET, SO_LINGER, (const char *)&opv, sizeof (opv));
#endif
#endif
#ifdef __gnu_linux__
        int rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &v, sizeof (v)); 
#endif

        if (rc == -1)
        {
            fprintf(stderr, "Setsocketopt Failed\n");
            close(sfd);
            return -1;
        }

        rc = bind(sfd, (const struct sockaddr *)&sin,
                sizeof (const struct sockaddr));
        if (rc != 0) 
        {
            fprintf(stderr, "Bind Failed\n");
            close(sfd);
            return -1;
        }   

    }
    else
    {
        int rc = connect(sfd, (const struct sockaddr *)&sin,
                sizeof (const struct sockaddr));

        if (rc != 0) 
        {
            fprintf(stderr, "Connect Failed\n");
            return -1;
        }   
    }

    return sfd;
}


int myread(SOCKET sfd, char buf[], int count)
{
    int n_readed = 0;
    while (n_readed != count) 
    {
        int n = read(sfd, buf + n_readed, count - n_readed);
        if (n == 0)
            break;
        if (n == -1)
            return -1;
        n_readed += n;
    }
    return n_readed;
}

int mywrite(SOCKET sfd, char buf[], int count)
{
    int n_writed = 0;
    while (n_writed != count) 
    {
        int n = write(sfd, buf + n_writed, count - n_writed);
        if (n == 0)
            break;
        if (n == -1)
            return -1;
        n_writed += n;
    }
    return n_writed;
}

char *tpath;
int port;

int main(int argc, char **argv)
{
    if (argc < 3) 
    {
        puts("Usage:./TransFile [FILE] [PORT]");
        return 1;
    }

    tpath = argv[1];
    port = strtol(argv[2], NULL, 10);

    FILE *fp = fopen(tpath, "rb+");

    if (NULL == fp)
    {
        perror("file open failed!");
        return 1;
    }

    Init();
    
    SOCKET con = MakeTcpSocket(NULL, port);
    
    if (con == -1)
    {
        perror("OH NO!!!!");
        return 1;
    }

    listen(con, 10);

    struct sockaddr_in sin;
    socklen_t len = sizeof (struct sockaddr);
    int fd = accept(con, (struct sockaddr *)&sin, &len);
    
    printf("Transfering...\n");
    if (fd == -1) 
    {
        perror("accept");
        return 1;
    }

    int n, nn;
    while (1)
    {
        n = nn = 0;
        n = fread(__commbuff, 1, sizeof (__commbuff), fp);
        
        if (n <= 0)
        {
            if (feof(fp))
                break;
        }
        nn = mywrite(fd, __commbuff, n);
            
        if (nn != n)
        {
                puts("file transfer exception! transfer failed!");
                return 1;
        }
    }

    close(fd);

    close(con);
    Clean();
    fclose(fp);
    return 0;
}


// 接受文件
import java.io.*;
import java.net.*;
import java.nio.Buffer;

public class GetFile {

	Socket socket;
	byte[] buffer;
	InputStream in;
	FileOutputStream fos;
	
	String filename;
	String addr;
	int port;
	
	public GetFile(String[] args) {
		// TODO Auto-generated constructor stub
		buffer = new byte[4096];
		
		filename = args[0];
		addr = args[1];
		port = Integer.parseInt(args[2]);
		
		try {
			fos = new FileOutputStream(filename);
			socket = new Socket(addr, port);
			in = socket.getInputStream();
			while (true) {
				int n = in.read(buffer);
				if (n <= 0)
				{
					fos.close();
					return;
				}
				fos.write(buffer, 0, n);
			}
			
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		if (args.length < 3) {
			System.out.println("Usage:java GetFile [FILE] [IPADDESS] [PORT]");
			return; //error
		}
		
		new GetFile(args);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值