//以下是tcpclient伺服器端的監聽程式,假設伺服器端和用戶端在同一台機器上,
//為了使用戶端可以使用localhost/127.0.0.1/192.168.1.2等多種情況,
//應該使用IPAddress.Any,而不是指定一個ip,以下是msdn的說明
//msdn
//此建構函式允許指定本地 IP 位址和用於偵聽傳入的連接嘗試的埠號。在調用該建構函式之前,必須首先使用所需的本//地位址創建 IPAddress。將此IPAddress 作為 localaddr參數傳遞給建構函式。如果您不介意分配哪個本地位址,//請將 localaddr 參數指定為 IPAddress.Any,這樣基礎服務提供程式將分配最適合的網路位址。如果您有多個網路接//口,這將有助於簡化您的應用程式。如果您不介意使用哪個本地埠,可以指定0 作為埠號。在這種情況下,服務提供//程式將分配一個介於 1024 和 5000 之間的可用埠號。如果使用這種方法,則可以使用 LocalEndpoint屬性探索所//分配的本地網路位址和埠號。
//以下是伺服器端的程式
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TcpReceive
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Thread thread = new Thread(new ThreadStart(MyListen));
thread.Start();
}
public void MyListen()
{
IPAddress localAddr = IPAddress.Parse("192.168.1.2");
Int32 port = 2112;
TcpListener tcpListen = new TcpListener(IPAddress.Any,port);
tcpListen.Start();
while (true)
{
TcpClient tcpClient = tcpListen.AcceptTcpClient();
NetworkStream ns = tcpClient.GetStream();
StreamReader sr = new StreamReader(ns);
string res = sr.ReadToEnd();
Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { res });
}
//tcpClient.Close();
//tcpListen.Stop();
}
public void UpdateDisplay(string text)
{
this.textBox1.Text += text;
}
protected delegate void UpdateDisplayDelegate(string Text);
}
}
//以下是用戶端程式
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace TcpSend
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TcpClient tcpClient = new TcpClient(this.textBox1.Text,int.Parse(this.textBox2.Text));
NetworkStream ns = tcpClient.GetStream();
FileStream fs = File.Open("d:\\123.txt",FileMode.Open);
int data = fs.ReadByte();
while (data != -1)
{
ns.WriteByte((byte)data);
data=fs.ReadByte();
}
fs.Close();
ns.Close();
tcpClient.Close();
}
}
}
全站熱搜
留言列表