//如下是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(); } } }