程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 簡單的C#Socket編程

簡單的C#Socket編程

編輯:關於C語言

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 connetct 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;
using System.Text;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
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

public static void Main()
{
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"

try
{
sb.Add("Conneting to Server");
myclient = new TcpClIEnt("localhost", 1234);
sb.Add("Conneted,Please enter something in the textbox");
}
catch
{
sb.Add(string.Format("Failed to connect to server at {0}:1234", "localhost"));
}
flag = true;
}

protected void ShowMessage()
{
for(int i=0;i {
t2.Items.Add((object)sb[i].ToString());
}
sb.Clear();
}

private void t1_TextChanged(object sender, System.EventArgs e)
{
if(t1.Text == "" )
btS.Enabled = false;
else
btS.Enabled=true;
}

private void btS_Click(object sender, System.EventArgs e)
{
if(t1.Text=="")
{
sb.Add( "Please enter something in the textbox.");
t1.Focus();
return ;
}
string s;
try
{
streamWriter.WriteLine(t1.Text);
Console.WriteLine("Sending Message");
streamWriter.Flush();
s= streamReader.ReadLine();
Console.WriteLine("Reading Message") ;
Console.WriteLine(s) ;
sb.Add(s);
t1.Text = "";
t1.Focus();
ShowMessage();
}
catch
{
MessageBox.Show("Error.");
}
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved