الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

server connect client

بدأه H!Ba في 24 مارس 2012 · 4 رد · 839 مشاهدة · في Microsoft Visual C#.NET
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

مسالخير

انا عندي كود للسرفر و كود للكلينت ع سي شارب لمل اشغل الكود كل واحد عادي بشتغل بس لما اعمل connect بعطيني error في كود سرفر في هيدا سطر

conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();

و بطلع من كو كلينت بليز ساعدوني

هيدا كود سرفر

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Asynchronous_Server
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
		IPEndPoint iep = new IPEndPoint(IPAddress.Any, 5020);
		private byte[] data = new byte[1024];
		private int size = 1024;
		private System.Windows.Forms.TextBox conStatus;
		private System.Windows.Forms.ListBox results;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//

		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.results = new System.Windows.Forms.ListBox();
            this.conStatus = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // results
            // 
            this.results.BackColor = System.Drawing.Color.AliceBlue;
            this.results.Dock = System.Windows.Forms.DockStyle.Fill;
            this.results.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(178)));
            this.results.Items.AddRange(new object[] {
            "Clients Transmissions ..."});
            this.results.Location = new System.Drawing.Point(0, 0);
            this.results.Name = "results";
            this.results.Size = new System.Drawing.Size(288, 174);
            this.results.TabIndex = 0;
            this.results.SelectedIndexChanged += new System.EventHandler(this.results_SelectedIndexChanged);
            // 
            // conStatus
            // 
            this.conStatus.BackColor = System.Drawing.Color.Gainsboro;
            this.conStatus.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.conStatus.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.conStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(178)));
            this.conStatus.Location = new System.Drawing.Point(0, 153);
            this.conStatus.Name = "conStatus";
            this.conStatus.ReadOnly = true;
            this.conStatus.Size = new System.Drawing.Size(288, 21);
            this.conStatus.TabIndex = 1;
            this.conStatus.Text = "Waiting for client...";
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(288, 174);
            this.Controls.Add(this.conStatus);
            this.Controls.Add(this.results);
            this.Name = "Form1";
            this.Text = "Asynchronous Server";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());

		}

		void AcceptConn(IAsyncResult iar)
		{
			Socket oldserver = (Socket)iar.AsyncState;
			Socket client = oldserver.EndAccept(iar);
			conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
			string stringData = "Welcome to my server";
			byte[] message1 = Encoding.ASCII.GetBytes(stringData);
			client.BeginSend(message1, 0, message1.Length, SocketFlags.None,new AsyncCallback(SendData), client);
            server.BeginAccept(new AsyncCallback(AcceptConn), server);
        }
		void SendData(IAsyncResult iar)
		{
			Socket client = (Socket)iar.AsyncState;
			int sent = client.EndSend(iar);
			client.BeginReceive(data, 0, size, SocketFlags.None,new AsyncCallback(ReceiveData), client);
		}
		void ReceiveData(IAsyncResult iar)
		{
			Socket client = (Socket)iar.AsyncState;
			int recv = client.EndReceive(iar);
			if (recv == 0)
			{
				client.Close();
				conStatus.Text = "Waiting for client...";
				server.BeginAccept(new AsyncCallback(AcceptConn), server);
				return;
			}
			string receivedData = Encoding.ASCII.GetString(data, 0, recv);
			results.Items.Add(receivedData);
			byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
			client.BeginSend(message2, 0, message2.Length, SocketFlags.None,new AsyncCallback(SendData), client);
		}
		void ButtonStopOnClick(object obj, EventArgs ea)
		{
			Close();
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
			server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
			IPEndPoint iep = new IPEndPoint(IPAddress.Any, 5020);
			server.Bind(iep);
			server.Listen(-1);
			server.BeginAccept(new AsyncCallback(AcceptConn), server);
		}

        private void results_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

	}}

و هيدا كود client

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ASyn_Client_Example
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private Socket client;
		private byte[] data = new byte[1024];
		private int size = 1024;

		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.TextBox newText;
		private System.Windows.Forms.ListBox results;
		private System.Windows.Forms.Button button2;
		private System.Windows.Forms.Button button3;
		private System.Windows.Forms.TextBox conStatus;
		private System.Windows.Forms.TextBox textBox1;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.button1 = new System.Windows.Forms.Button();
            this.newText = new System.Windows.Forms.TextBox();
            this.results = new System.Windows.Forms.ListBox();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.conStatus = new System.Windows.Forms.TextBox();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Enabled = false;
            this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.button1.Location = new System.Drawing.Point(328, 24);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 56);
            this.button1.TabIndex = 0;
            this.button1.Text = "Send";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // newText
            // 
            this.newText.BackColor = System.Drawing.Color.Azure;
            this.newText.Location = new System.Drawing.Point(16, 24);
            this.newText.Name = "newText";
            this.newText.ReadOnly = true;
            this.newText.Size = new System.Drawing.Size(304, 20);
            this.newText.TabIndex = 1;
            this.newText.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.newText_KeyPress);
            // 
            // results
            // 
            this.results.BackColor = System.Drawing.Color.LightCyan;
            this.results.Location = new System.Drawing.Point(16, 56);
            this.results.Name = "results";
            this.results.Size = new System.Drawing.Size(304, 95);
            this.results.TabIndex = 2;
            this.results.SelectedIndexChanged += new System.EventHandler(this.results_SelectedIndexChanged);
            // 
            // button2
            // 
            this.button2.Enabled = false;
            this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.button2.Location = new System.Drawing.Point(328, 128);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 24);
            this.button2.TabIndex = 3;
            this.button2.Text = "Disconnect";
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // button3
            // 
            this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.button3.Location = new System.Drawing.Point(328, 160);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(75, 24);
            this.button3.TabIndex = 4;
            this.button3.Text = "Connect";
            this.button3.Click += new System.EventHandler(this.button3_Click);
            // 
            // conStatus
            // 
            this.conStatus.BackColor = System.Drawing.SystemColors.InactiveBorder;
            this.conStatus.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.conStatus.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.conStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(178)));
            this.conStatus.Location = new System.Drawing.Point(0, 187);
            this.conStatus.Name = "conStatus";
            this.conStatus.Size = new System.Drawing.Size(408, 21);
            this.conStatus.TabIndex = 5;
            this.conStatus.Text = "Disconnected";
            // 
            // textBox1
            // 
            this.textBox1.BackColor = System.Drawing.Color.Azure;
            this.textBox1.Location = new System.Drawing.Point(16, 160);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(304, 20);
            this.textBox1.TabIndex = 6;
            this.textBox1.Text = "127.0.0.1";
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.BackColor = System.Drawing.SystemColors.Control;
            this.ClientSize = new System.Drawing.Size(408, 208);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.conStatus);
            this.Controls.Add(this.newText);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.results);
            this.Controls.Add(this.button1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Asynchronous Client";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}
		void ReceiveData(IAsyncResult iar)
		{
			try
			{
			Socket remote = (Socket)iar.AsyncState;
			int recv = remote.EndReceive(iar);
			string stringData = Encoding.ASCII.GetString(data, 0, recv);
			results.Items.Add(stringData);
			}
			catch(Exception ex){MessageBox.Show(ex.Message);}

			}
		void SendData(IAsyncResult iar)
		{
			try
			{
			Socket remote = (Socket)iar.AsyncState;
			int sent = remote.EndSend(iar);
			remote.BeginReceive(data, 0, size, SocketFlags.None,
				new AsyncCallback(ReceiveData), remote);
			}
			catch(Exception ex){MessageBox.Show(ex.Message);}

			}

		void Connected(IAsyncResult iar)
		{
			client = (Socket)iar.AsyncState;
			try
			{
				client.EndConnect(iar);
				conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
				client.BeginReceive(data, 0, size, SocketFlags.None,
					new AsyncCallback(ReceiveData), client);
			} 
			catch (SocketException)
			{
				conStatus.Text = "Error connecting";
			}
		}
		private void Form1_Load(object sender, System.EventArgs e)
		{

		}

		private void button1_Click(object sender, System.EventArgs e)
		{
			try
			{
				byte[] message = Encoding.ASCII.GetBytes(newText.Text);
				newText.Clear();
				client.BeginSend(message, 0, message.Length, SocketFlags.None,new AsyncCallback(SendData), client);
				newText.Focus();
			}
			catch(Exception ex){MessageBox.Show(ex.Message);}
		}

		private void button3_Click(object sender, System.EventArgs e)
		{
		try
		{
			conStatus.Text = "Connecting...";
			Socket newsock = new Socket(AddressFamily.InterNetwork,
			SocketType.Stream, ProtocolType.Tcp);
			IPEndPoint iep = new IPEndPoint(IPAddress.Parse(textBox1.Text), 5020);
			newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
			newText.Focus();
			button1.Enabled = true;
			button2.Enabled = true;
			newText.ReadOnly = false;

		}
		catch(Exception ex){MessageBox.Show(ex.Message);}

		}

		private void button2_Click(object sender, System.EventArgs e)
		{
			client.Close();
			button1.Enabled = false;
			button2.Enabled = false;
			newText.ReadOnly = true;
			conStatus.Text = "Disconnected";
		}

		private void newText_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
		{
			if (button1.Enabled == true)
			if(e.KeyChar == '\r')
			{
				button1_Click(sender,e);
			}
		}

        private void results_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
	}
}
#2

السلام عليكم

اكيد راح يطلع غلط لانه عند تعديل اي control في الفورم لازم نستخدم ال delegate لما نشتغل على network programming

لانو التعديل وقتها بيصير من اكتر من thread على نفس الكونترول وهيك خطأ

للتعديل الغي التعديل المباشر على الكونترول اللي هو

conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();

واستبدليه بفنكشن تستخدم ال delegate للتعديل

  UpdateTexBox("Connected to: " + client.RemoteEndPoint.ToString());

وهادي هيه الفنكشن اللي راح نكتبها

 public delegate void updateTxt(string txt);
        private void UpdateTexBox(string Text)
        {
            if (conStatus.InvokeRequired)
            {
                conStatus.BeginInvoke(new updateTxt(UpdateTexBox), Text);
            }
            else
            {
                conStatus.Text = Text;
            }

        }

طبعا لازم تستخدمي هادي الطريقه في كل مكان بدك تعدليه فيه اشي بالفورم

بالتوفيق

1
#3

يسلمو أخي غلبتك

لما عملت هذه الطريقه زبط ما طلعلي error بس بطلع من server و client لما أعمل connect

#4

شو الايرور اللي طلع ؟؟

هو بيطلع الايرور مش بسبب الكونكت بسبب انك بتحاول تعدلي على الكونترول

مبدئيا اتاكدي انو بطلتي تعدلي ولا على اي كونترول بشكل مباشر في الكلينت والسيرفر كمان وازا ضل الايرور لو سمحتى نزلي الكود اشوفو

1
#5

شكرا خيي هلأ ما في و لا error شكرا

مواضيع مشابهة