using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

public class MyServer : MonoBehaviour {

void Start () {
TcpListener tcp_Listener = new TcpListener(1024);
tcp_Listener.Start();
TcpClient tcp = tcp_Listener.AcceptTcpClient();
Socket s = tcp.Client;
NetworkStream ns = tcp.GetStream();
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
sw.AutoFlush = true;
// 
byte [] b = new byte[int.Parse (sr.ReadLine())];
// 數字要與客戶端一樣
int buffer = 8192;
int i;
for(i = 0; i < b.Length-buffer; i+=buffer){
s.Receive(b, i, buffer, SocketFlags.None);
sw.WriteLine("ok"); // 接收完成,通知客戶端
}
//
sw.WriteLine("ok");
s.Receive(b, i, b.Length - i, SocketFlags.None);
// Close Server
tcp_Listener.Stop ();
tcp.Close ();
// 下載路徑,寫入檔案
File.WriteAllBytes ("C:/Audio/B.jpg", b);
print ("Download Finish !!");
}
}


using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

public class MyClient : MonoBehaviour {


#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
string path = @"C:\Users\Test\Desktop\Data2\A.jpg"; // PC Path
#elif UNITY_ANDROID
string path = "/mnt/sdcard/A.jpg"; // Android Path
#endif

void OnGUI() {
if(GUI.Button(new Rect(10,10,100,50), "Send File")){
TcpClient tcp = new TcpClient("61.64.241.39", 1024); // IP , Port
Socket s = tcp.Client;
NetworkStream ns = tcp.GetStream();
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
sw.AutoFlush = true;
//
FileStream f = new FileStream (path, FileMode.Open);
sw.WriteLine (f.Length);
//
//
byte [] b = new byte[f.Length];
f.Read (b, 0, b.Length);
// // 數字要與伺服器一樣
int buffer = 8192;
int i;
for(i = 0; i < b.Length-buffer; i+=buffer){
s.Send(b,i,buffer, SocketFlags.None);
sr.ReadLine(); // 接收 ok
}
sr.ReadLine(); // 接收 ok
//
s.Send(b,i,b.Length - i, SocketFlags.None);
// Close File & TCP Socket
f.Close ();
sw.Close();
sr.Close();
s.Close();
tcp.Close ();
}
}

}

arrow
arrow
    全站熱搜

    黃彥霖 發表在 痞客邦 留言(1) 人氣()