您的位置:首页 > 理论基础 > 计算机网络

C#:TcpClient(客户端) and TcpServer(服务端)

2009-10-08 23:02 621 查看
服务端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using System.Net.Sockets;
using System.Net;

namespace PictureClient
{
/// <summary>
/// Interaction logic for PictureClientWindow.xaml
/// </summary>
public partial class PictureClientWindow : Window
{
private const int bufferSize = 8192;
public PictureClientWindow()
{
InitializeComponent();
}

private TcpClient ConnectToServer()
{
TcpClient client = new TcpClient();
IPHostEntry host = Dns.GetHostEntry(Properties.Settings.Default.Server);
var address = (from h in host.AddressList
where h.AddressFamily == AddressFamily.InterNetwork
select h).First();
client.Connect(
address.ToString(), Properties.Settings.Default.ServerPort);
return client;
}

private void buttonGetPictureList_Click(object sender, RoutedEventArgs e)
{
//send data
TcpClient client = ConnectToServer();
NetworkStream clientStream = client.GetStream();
string request = "LIST";
byte[] requestBuffer = Encoding.ASCII.GetBytes(request);
clientStream.Write(requestBuffer, 0, requestBuffer.Length);

//read response
byte[] responseBuffer = new byte[bufferSize];
MemoryStream memStream = new MemoryStream();
int bytesRead = 0;
do
{
bytesRead = clientStream.Read(responseBuffer, 0, bufferSize);
memStream.Write(responseBuffer, 0, bytesRead);

} while (bytesRead > 0);
clientStream.Close();
client.Close();

byte[] buffer = memStream.GetBuffer();
string response = Encoding.ASCII.GetString(buffer);
this.DataContext = response.Split(':');
}

private void buttonGetpicture_Click(object sender, RoutedEventArgs e)
{
TcpClient client = ConnectToServer();

NetworkStream clientStream = client.GetStream();
string request = "FILE:" + this.listBoxFiles.SelectedItem.ToString();
byte[] requestBuffer = Encoding.ASCII.GetBytes(request);
clientStream.Write(requestBuffer, 0, requestBuffer.Length);

byte[] responseBuffer = new byte[bufferSize];
MemoryStream memStream = new MemoryStream();
int bytesRead = 0;
do
{
bytesRead = clientStream.Read(responseBuffer, 0, bufferSize);
memStream.Write(responseBuffer, 0, bytesRead);

} while (bytesRead > 0);
clientStream.Close();
client.Close();

if (memStream.GetBuffer().Length != 0)
{
BitmapImage bitmapImage = new BitmapImage();
memStream.Seek(0, SeekOrigin.Begin);
bitmapImage.BeginInit();
bitmapImage.StreamSource = memStream;
bitmapImage.EndInit();
pictureBox.Source = bitmapImage;
}
}
}
}


客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace PictureServer
{
internal static class PictureHelper
{
internal static IEnumerable<string> GetFileList()
{
return from file in Directory.GetFiles(Properties.Settings.Default.PictureDirectory)
select Path.GetFileName(file);
}

internal static byte[] GetFileListBytes()
{
try
{
IEnumerable<string> files = PictureHelper.GetFileList();
StringBuilder responseMessage = new StringBuilder();
foreach (string s in files)
{
responseMessage.Append(s);
responseMessage.Append(":");
}
return Encoding.ASCII.GetBytes(responseMessage.ToString());
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
class Program
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Any,
Properties.Settings.Default.Port);
listener.Start();
Console.WriteLine("Server running...");

while (true)
{
const int bufferSize = 8192;

TcpClient client = listener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();

byte[] buffer = new byte[bufferSize];
int readBytes = 0;
readBytes = clientStream.Read(buffer, 0, bufferSize);

string request =
Encoding.ASCII.GetString(buffer).Substring(0, readBytes);

if (request.StartsWith("LIST", StringComparison.Ordinal))
{
byte[] responseBuffer = PictureHelper.GetFileListBytes();
clientStream.Write(responseBuffer, 0, responseBuffer.Length);
}
else if (request.StartsWith("FILE", StringComparison.Ordinal))
{
string[] requestMessage = request.Split(':');
string filename = requestMessage[1];
try
{
byte[] data =
File.ReadAllBytes(
Path.Combine(Properties.Settings.Default.PictureDirectory, filename)
);
clientStream.Write(data, 0, data.Length);
}

catch(IOException e)
{
Console.WriteLine("IOException: " + e.Message);
}
catch(WebException e)
{
Console.WriteLine("WebException: " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Other Exception: " + e.Message);
}
}
clientStream.Close();
}
}
}
}


附客户端WPF代码:

<Window x:Class="PictureClient.PictureClientWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Picture Client" Height="329" Width="616">
<Grid Name="PictureClient">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="19*" />
<ColumnDefinition Width="563*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="85*" />
<RowDefinition Height="21*" />
<RowDefinition Height="13*" />
<RowDefinition Height="23*" />
<RowDefinition Height="29*" />
<RowDefinition Height="120*" />
</Grid.RowDefinitions>
<Image x:Name="pictureBox" Grid.RowSpan="12" Margin="6,0,6,10" Grid.ColumnSpan="12" />
<Button HorizontalAlignment="Right" Margin="0,21,18,40" Name="buttonGetPictureList" Width="168" Click="buttonGetPictureList_Click" Grid.Column="1">Get Picture List</Button>
<Button Grid.Row="5" Height="28" HorizontalAlignment="Right" Margin="0,0,17,10" Name="buttonGetpicture" VerticalAlignment="Bottom" Width="169" Click="buttonGetpicture_Click" Grid.Column="1">Get Picture</Button>
<ListBox ItemsSource="{Binding}" Grid.RowSpan="6" HorizontalAlignment="Right" Margin="0,54,19,47" Name="listBoxFiles" Width="167" Grid.Column="1" />
</Grid>
</Window>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐