天天看點

簡單的C#Socket程式設計

server,伺服器代碼。

使用Socket套接字連接配接。

using System;

using System.Net;

using System.Net.Sockets;

using System.IO ;

public class Echoserver

{

//entry point of main method.

public static void Main()

//TcpListener is listening on the given port

Int32 port = 1234;

//IPAddress is co.Netct ip address

//IPAddress addr = IPAddress.Parse("127.0.0.1");

IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];

TcpListener tcpListener = new TcpListener(ipAddress,port);

tcpListener.Start();

Console.WriteLine("Server Started") ;

//Accepts a new connection

Socket socketForClient = tcpListener.AcceptSocket();

//StreamWriter and StreamReader Classes for reading and writing the data to and from.

//The server reads the meassage sent by the Client ,converts it to upper case and sends it back to the client.

//Lastly close all the streams.

try

if (socketForClient.Connected)

while(true)

Console.WriteLine("Client connected");

.NetworkStream.NetworkStream = new.NetworkStream(socketForClient);

StreamWriter streamWriter = new StreamWriter.NetworkStream);

StreamReader streamReader = new StreamReader.NetworkStream);

string line = streamReader.ReadLine();

Console.WriteLine("Read:" +line);

line=line.ToUpper()+ "!";

streamWriter.WriteLine(line);

Console.WriteLine("Wrote:"+line);

streamWriter.Flush() ;

}

}

socketForClient.Close();

Console.WriteLine("Exiting");

catch(Exception e)

Console.WriteLine(e.ToString()) ;

Client,用戶端程式,在文本框中輸入字元,将在清單框顯示。

using System.Text;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.IO;

namespace SocketSample

public class Sample : System.Windows.Forms.Form

private System.Windows.Forms.Button btS;

private System.Windows.Forms.TextBox t1;

private.NetworkStream.NetworkStream ;

private StreamReader streamReader ;

private StreamWriter streamWriter ;

ArrayList sb;

TcpClient myclient;

bool flag=false;

private System.Windows.Forms.ListBox t2;

private System.ComponentModel.Container components = null;

public Sample()

sb = new ArrayList();

InitializeComponent();

if(!flag)

Connect();

//get a.Network stream from the server

.NetworkStream = myclient.GetStream();

streamReader = new StreamReader.NetworkStream);

streamWriter = new StreamWriter.NetworkStream);

ShowMessage();

protected override void Dispose( bool disposing )

if( disposing )

if(components != null)

components.Dispose();

base.Dispose( disposing );

Windows 窗體設計器生成的代碼#region Windows 窗體設計器生成的代碼

/**////

/// 設計器支援所需的方法 - 不要使用代碼編輯器修改

/// 此方法的内容。

///

private void InitializeComponent()

System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Sample));

this.t1 = new System.Windows.Forms.TextBox();

this.btS = new System.Windows.Forms.Button();

this.t2 = new System.Windows.Forms.ListBox();

this.SuspendLayout();

//

// t1

this.t1.Location = new System.Drawing.Point(24, 32);

this.t1.Name = "t1";

this.t1.Size = new System.Drawing.Size(280, 21);

this.t1.TabIndex = 0;

this.t1.Text = "";

this.t1.TextChanged += new System.EventHandler(this.t1_TextChanged);

// btS

this.btS.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btS.BackgroundImage")));

this.btS.Enabled = false;

this.btS.FlatStyle = System.Windows.Forms.FlatStyle.Popup;

this.btS.Location = new System.Drawing.Point(320, 32);

this.btS.Name = "btS";

this.btS.TabIndex = 1;

this.btS.Text = "Send";

this.btS.Click += new System.EventHandler(this.btS_Click);

// t2

this.t2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t2.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));

this.t2.ItemHeight = 15;

this.t2.Location = new System.Drawing.Point(24, 64);

this.t2.Name = "t2";

this.t2.Size = new System.Drawing.Size(368, 212);

this.t2.TabIndex = 2;

// Sample

this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));

this.ClientSize = new System.Drawing.Size(416, 297);

this.Controls.Add(this.t2);

this.Controls.Add(this.btS);

this.Controls.Add(this.t1);

this.Name = "Sample";

this.Text = "Sample";

this.ResumeLayout(false);

#endregion

Sample df=new Sample();

df.FormBorderStyle=FormBorderStyle.Fixed3D;

Application.Run(df);

protected void Connect()

{

//connect to the "localhost" at the give port

//if you have some other server name then you can use that instead of "localhost"

sb.Add("Co.Neting to Server");

myclient = new TcpClient("localhost", 1234);

sb.Add("Co.Neted,Please enter something in the textbox");

catch

sb.Add(string.Format("Failed to connect to server at {0}:1234", "localhost"));

flag = true;