⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 class1.cs

📁 Csharp网络应用案例导航 Csharp网络应用案例导航
💻 CS
字号:
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;

namespace SimplestChatConsole
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		private Socket soc;
		private Socket clientSoc;
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			//
			// TODO: Add code to start application here
			//
			Class1 example;
			bool isServer=false;
			System.Console.Out.WriteLine("Is the endpoint the server?\nY/N");
			char c=(char)System.Console.Read();
			if(c=='y'||c=='Y')
				isServer=true;
			example=new Class1(isServer);
			if(isServer)
				example.ServerSide();
			else
				example.ClientSide();
		}

		public Class1(bool isServer)
		{
			IPEndPoint ep;
			IPAddress ip=Dns.GetHostByName("localhost").AddressList[0];
			if(isServer)
				ep=new IPEndPoint(ip,999);
			else
				ep=new IPEndPoint(ip,998);
			soc=new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
			soc.Bind(ep);
		}

		public void ServerSide()
		{
			int count;
			soc.Listen(1);
			System.Console.WriteLine("Begin Listening...");
			clientSoc=soc.Accept();
			System.Console.WriteLine("Got a client");
			System.Console.ReadLine();
			string input="Hello";
			byte[] buf=new byte[1024];
			while(input!="\\q")
			{
				clientSoc.Send(Encoding.Default.GetBytes(input));
				count=clientSoc.Receive(buf);
				System.Console.WriteLine(Encoding.Default.GetString(buf,0,count));
				input=System.Console.ReadLine();
			}
			clientSoc.Close();
			soc.Close();
		}

		public void ClientSide()
		{
			int count;
			IPEndPoint ep;
			byte[] buf=new byte[1024];
			IPAddress ip=Dns.GetHostByName("localhost").AddressList[0];
			ep=new IPEndPoint(ip,999);
			soc.Connect(ep);
			if(soc.Connected)
				System.Console.WriteLine("Successfully Connected to the Server");
			string input="Hello";
			System.Console.ReadLine();
			while(input!="\\q")
			{
				count=soc.Receive(buf);
				System.Console.WriteLine(Encoding.Default.GetString(buf,0,count));
				input=System.Console.ReadLine();
				soc.Send(Encoding.Default.GetBytes(input));
			}
			soc.Close();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -