TCP_Server
接收client端發送之文字
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TCP_Server
{
class Program
{
public static void Main()
{
// IPAddress :建立一個 IP 位址 (本機位置IP)
IPAddress ipAddr = IPAddress.Parse("192.168.0.43");
IPEndPoint ipep = new IPEndPoint(ipAddr, 1000); //前者為IP位址,後者為port (本機)
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep); //建立連結
newsock.Listen(10); //使之可接收
while (true)
{
Socket client = newsock.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; //RemoteEndPoint取得發送方IP
Console.WriteLine("Client End Point = " + clientep);
Console.WriteLine("等待client端資料");
// create a new thread and then receive message.
TcpListener listener = new TcpListener(client);
Thread thread = new Thread(new ThreadStart(listener.run));
thread.Start();
}
// newsock.Close();
}
}
public class TcpListener
{
Socket socket;
public TcpListener(Socket s)
{
socket = s;
}
public void run()
{
while (true)
{
byte[] data = new byte[1024];
int recv = socket.Receive(data);
if (recv == 0) break;
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
}
socket.Close();
}
}
}
--------------------------------------------------------------------------------------------
接收client端發送之檔案
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TCP_Server
{
class Program
{
public static void Main()
{
// IPAddress :建立一個 IP 位址 (本機位置IP)
IPAddress ipAddr = IPAddress.Parse("192.168.0.43");
IPEndPoint ipep = new IPEndPoint(ipAddr, 1000); //前者為IP位址,後者為port (本機)
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep); //建立連結
newsock.Listen(10); //使之可接收
while (true)
{
Socket client = newsock.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; //RemoteEndPoint取得發送方IP
Console.WriteLine("Client End Point = " + clientep);
Console.WriteLine("等待client端資料");
// create a new thread and then receive message.
TcpListener listener = new TcpListener(client);
Thread thread = new Thread(new ThreadStart(listener.run));
thread.Start();
}
// newsock.Close();
}
}
public class TcpListener
{
Socket socket;
public TcpListener(Socket s)
{
socket = s;
}
public void run()
{
while (true)
{
byte[] data = new byte[1024];
int recv = socket.Receive(data);
if (recv == 0) break;
Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
}
socket.Close();
}
}
}
--------------------------------------------------------------------------------------------
接收client端發送之檔案
留言
張貼留言