這裡介紹一下TCPClient類和Socket類,主要以兩個例子分析一下這兩個類在接收發送資料上的不同
TCP樣本:
TCP Sender, 發送資料到server端
using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCPSender
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient(textBox1.Text, Int32.Parse(textBox2.Text));//textBox1用來輸入地址,textBox2用來輸入訪問連接埠
NetworkStream ns = client.GetStream();
FileStream fs = File.Open("Form1.cs", FileMode.Open);
int data = fs.ReadByte();
while (data != -1)
{
ns.WriteByte((byte)data);
data = fs.ReadByte();
}
fs.Close();
ns.Close();
client.Close();
}
}
}
TCP Receiver, 監聽並接收資料
using System;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCPReceiver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Thread thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
public void Listen()
{
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
Int32 port = 2112;
TcpListener listener = new TcpListener(localAddr, port);
listener.Start();
TcpClient tcpClient = listener.AcceptTcpClient();
NetworkStream ns = tcpClient.GetStream();
StreamReader sr = new StreamReader(ns);
string result = sr.ReadToEnd();
Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });
tcpClient.Close();
listener.Stop();
}
public void UpdateDisplay(string text)
{
textBox1.Text = text;
}
protected delegate void UpdateDisplayDelegate(string text);
}
}
最後執行結果如下:
Socket樣本
Socket資訊發送端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace SocketSenderConsole
{
class Program
{
static void Main(string[] args)
{
byte[] receivedBytes = new byte[1024];
//use the local host to create a IPEndPoint, which is connection end point
IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 2112);
Console.WriteLine("Starting: Creating Socket object.");
//to create a sender
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipEndPoint);
string sendingMessage = "Hello World Socket Test";
Console.WriteLine("Creating message: Hello World Socket Test");
byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
//send messages
sender.Send(forwardMessage);
//receive the server response
int totalBytesReceived = sender.Receive(receivedBytes);
Console.WriteLine("Message provided from server: {0}", Encoding.ASCII.GetString(receivedBytes, 0, totalBytesReceived));
//shut down and dispose
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadLine();
}
}
}
socket資訊監聽端:
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace SockedListener
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting: Creating Socket object.");
//The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration.
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 2112));
listener.Listen(10);
while(true)
{
Console.WriteLine("Waiting for connection on port 2112");
//The Accept method processes any incoming connection requests and returns a Socket that you can use to communicate data with the remote host.
Socket socket = listener.Accept();
string receivedValue = string.Empty;
while(true)
{
byte[] receivedBytes = new byte[1024];
int numBytes = socket.Receive(receivedBytes);
Console.WriteLine("Receiving ...");
receivedValue += Encoding.ASCII.GetString(receivedBytes, 0, numBytes);
if (receivedValue.IndexOf("[FINAL]") > -1)
{
break;
}
}
Console.WriteLine("Received value: {0}", receivedValue);
string replyValue = "Message successfully received.";
byte[] replyMessage = Encoding.ASCII.GetBytes(replyValue);
socket.Send(replyMessage);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
listener.Close();
}
}
執行結果: