C#:tcpclient (client) and TCPServer (service side)

Source: Internet
Author: User

Service side:

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> Publ IC partial class Pictureclientwindow:window {Private Const int buffersize = 8192; public Pictureclientwindow () {Initia Lizecomponent (); 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). A (); 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); (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); (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; } } } }

Client:

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 to 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 ()); The catch (System.Exception ex) {Console.WriteLine (ex). message); Throw Class Program {static void Main (string[] args) {TcpListener listener = new TcpListener (Ipaddress.any, PROPERTIES.S Ettings. 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 (); } } } }

Attach client WPF code:

<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= "a" margin= "6,0,6,10" grid.columnspan= "a"/> <button Horizontalalignment= "Right" margin= "0,21,18,40" name= "buttongetpicturelist" width= "click=" Buttongetpicturelist_click "grid.column=" 1 ">get picture list</button> <button grid.row=" 5 "Height=" "Ho"Rizontalalignment= "Right" margin= "0,0,17,10" name= "Buttongetpicture" verticalalignment= "Bottom" width= "169" 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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.