class Program
{
static void Main(string[] args)
{
Start();
}
public static void Start()
{
Console.WriteLine("启动聊天服务器");
CreateTcpServer("192.168.0.109", 2000); //这里开启Tcp服务器,在这里断点
Console.Read();
}
public static bool CreateTcpServer(string ip, int listenPort)
{
Socket _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ;
IPHostEntry hostEntry = null;
int _port = 2000;
foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if(address.AddressFamily.ToString()=="InterNetwork")
{
try
{
IPAddress hostIP = address;
IPEndPoint ipe = new IPEndPoint(address, _port);
_listener.Bind(ipe);
_listener.Listen(20);
while (true)
{
Socket socket = _listener.Accept();
byte[] receive = new byte[1024];
socket.Receive(receive);
Console.WriteLine("接收到消息:" + Encoding.ASCII.GetString(receive));
byte[] send = Encoding.ASCII.GetBytes("Success receive the message,send the back the message");
socket.Send(send);
Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(send));
// break;
}
}
catch (System.Exception)
{
return false;//这里一般会抛出一个异常,可以通过打印等操作显示
}
}
}
return true;
}
}
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Reflection;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApplication1
{
public class Context
{
private State state; // 状态,通过设置这个状态来产生不同的事情,State类是个接口,方法是不同实现的小弟
public void ProduceMusic()
{
state.ProduceMusic();
}
public void SetState(State state)
{
this.state = state;
}
}
//状态接口
public interface State
{
void ProduceMusic();
}
// 具体的状态类
public class BirdSingingState : State
{
public void ProduceMusic()
{
Console.WriteLine("Bird produce sound");
Console.Read();
}
}
class client
{
static void RunClient()
{
//Step1: create a binding with just HTTP
CustomBinding binding = new CustomBinding();
binding.Elements.Add(new HttpTransportBindingElement());
//Step2: use the binding to build the channel factory
IChannelFactory<IRequestChannel> factory =
binding.BuildChannelFactory<IRequestChannel>(
new BindingParameterCollection());
//open the channel factory
factory.Open();
//Step3: use the channel factory to create a channel
IRequestChannel channel = factory.CreateChannel(
new EndpointAddress("http://localhost:8080/channelapp"));
channel.Open();
//Step4: create a message
Message requestmessage = Message.CreateMessage(
MessageVersion.Soap12WSAddressing10,
"http://contoso.com/someaction",
"This is the body data");
//send message
Message replymessage = channel.Request(requestmessage);
Console.WriteLine("Reply message received");
Console.WriteLine("Reply action: {0}",
replymessage.Headers.Action);
string data = replymessage.GetBody<string>();
Console.WriteLine("Reply content: {0}", data);
//Step5: don't forget to close the message
requestmessage.Close();
replymessage.Close();
//don't forget to close the channel
channel.Close();
//don't forget to close the factory
factory.Close();
}
public static void f2()
{
while (true)
{
Console.WriteLine("F2");
}
}
public static void f1()
{
while (true)
{
Console.WriteLine("F1");
}
}
public class Automobile
{
// No implementation. All members are inherited from Object.
}
/// <summary>
/// 手机抽象类,即装饰者模式中的抽象组件类
/// </summary>
public abstract class Phone
{
public abstract void Print();
}
/// <summary>
/// 苹果手机,即装饰着模式中的具体组件类
/// </summary>
public class ApplePhone : Phone
{
/// <summary>
/// 重写基类方法
/// </summary>
public override void Print()
{
Console.WriteLine("开始执行具体的对象——苹果手机");
}
}
public abstract class Apple
{
public abstract void Speak();
}
public class Decorator : Apple
{
private Apple apple;
public Decorator(Apple apple)
{
this.apple = apple;
}
//public Decorator(Apple apple)
//{
// this.apple = apple;
//}
public override void Speak()
{
if (apple != null)
{
apple.Speak();
}
}
}
public class Hongfushi : Apple
{
public override void Speak()
{
Console.WriteLine("这是牛顿发现的苹果");
}
}
public class BigApple : Decorator
{
public BigApple(Apple apple) : base(apple)
{
}
public override void Speak()
{
base.Speak();
BigAppleSpeak();
}
public void BigAppleSpeak()
{
Console.WriteLine("this is a big red Apple");
}
}
public class GetSocket
{
//public List CreateSQL(string TableName, List ColName)
//{
// List SQLInfo = new List();
// StringBuilder CreateSel = new StringBuilder(" 查询语句:\nselect ");
// StringBuilder CreateUpd = new StringBuilder();
// CreateUpd.AppendFormat("\n\n更改语句:\n update {0} set ", TableName);
// StringBuilder CreateInser = new StringBuilder();
// CreateInser.AppendFormat("\n\n插入语句:\n INSERT INTO {0} ( ", TableName);
// StringBuilder Values = new StringBuilder(") values (");
// StringBuilder CreateDel = new StringBuilder("\n\n删除语句:\n delete from ");
// CreateDel.AppendFormat("{0} where <搜索条件>", TableName);
// int count = 1;
// foreach (string Item in ColName)
// {
// if (count == ColName.Count)
// {
// CreateSel.AppendFormat("{0}", Item);
// CreateUpd.AppendFormat("\n{0}=<{1}>", Item, Item);
// CreateInser.AppendFormat("\n{0}", Item);
// Values.AppendFormat("'{0}')", Item);
// }
// else
// {
// CreateSel.AppendFormat("{0},", Item);
// CreateUpd.AppendFormat("\n{0}=<{1}>,", Item, Item);
// CreateInser.AppendFormat("\n{0},", Item);
// Values.AppendFormat("'{0}',", Item);
// }
// count++;
// }
// CreateUpd.Append(" where <搜索条件>");
// CreateSel.AppendFormat(" from {0}", TableName);
// CreateInser.Append(Values.ToString());
// SQLInfo.Add(CreateSel.ToString());
// SQLInfo.Add(CreateInser.ToString());
// SQLInfo.Add(CreateUpd.ToString());
// SQLInfo.Add(CreateDel.ToString());
// return SQLInfo;
//}
public static void Main(string[] args)
{
#region xx
//Console.WriteLine("Press [ENTER] when service is ready");
//Console.ReadLine();
//RunClient();
//Console.WriteLine("Press [ENTER] to exit");
//Automobile firstAuto = new Automobile();
//Console.WriteLine(firstAuto);
//List<string> list = new List<string> { "1","2"};
//int[] nu = { };
//string first = list.FirstOrDefault(i=>i=="");
Thread t1 = new Thread(f1);
Thread t2 = new Thread(new ThreadStart(f2));
//t1.Start();
//t2.Start();
//var allType = Assembly.GetEntryAssembly().GetReferencedAssemblies()
// .Select(Assembly.Load)
// .SelectMany(y => y.DefinedTypes)
// .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
//BirdSingingState birdSing = new BirdSingingState();
//Context ctx = new Context();
//ctx.SetState(birdSing);
//ctx.ProduceMusic();
// 我买了个苹果手机
Phone phone = new ApplePhone();
Apple apple = new Hongfushi();
现在想贴膜了
//Decorator applePhoneWithSticker = new Sticker(phone);
扩展贴膜行为
//applePhoneWithSticker.Print();
//Console.WriteLine("----------------------\n");
现在我想有挂件了
//Decorator applePhoneWithAccessories = new Accessories(phone);
扩展手机挂件行为
//applePhoneWithAccessories.Print();
//Console.WriteLine("----------------------\n");
// 现在我同时有贴膜和手机挂件了
BigApple bigApple = new BigApple(apple);
//GoodTasteApple goodTasteApple = new GoodTasteApple(apple);
//bigApple.Speak();
//goodTasteApple.Speak();
//GoodTasteApple goodTasteApple2 = new GoodTasteApple(bigApple);
//goodTasteApple2.Speak();
#endregion
//StringBuilder update = new StringBuilder();
//update.AppendFormat("\n\n更改语句: \n update {0} set", "temp");
//update.AppendFormat("\n{0}=<{1}>", "MO_CODE","3" );
//List<int> list = new List<int> { 1 };
//int t=list.RemoveAll(item => item == 2);
//Console.WriteLine(update);
//Console.Read();
ConsoleApplication7.MathServiceReference.MathServiceSoapClient mathService = new ConsoleApplication7.MathServiceReference.MathServiceSoapClient();
string str=mathService.Add(1, 2);
JObject obj=(JObject)JsonConvert.DeserializeObject(str);
// JArray j = JArray.Parse(str);
//foreach(JObject obj in j)
// {
Console.WriteLine(obj["id"]);
// }
string time = "2018-08-03 17:00:00";
DateTime dt = Convert.ToDateTime(time);
Console.WriteLine(dt);
Console.WriteLine(mathService.Add(2,2));
// Console.ReadLine();
string host;
int port = 2000;
if (args.Length == 0)
{
//if no server name is passed as argument to this program
//use the current host name as the default.
host = Dns.GetHostName();
}
else
{
host = args[0];
}
string result = GetSocket.SocketSendReceive(host, port);
// Console.WriteLine(result);
Console.ReadLine();
ThreadSafe thread = new ThreadSafe();
thread.AddToTotal(1);
string s = "abc";
byte[] numbers = { 0x1f };
byte[] other = new byte[13];
numbers.CopyTo(other, 2);
// s = s.Substring(0, 2);
Console.WriteLine(numbers.Length);
foreach (var o in other)
{
Console.WriteLine("\n" + o);
}
Console.ReadLine();
}
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("192.168.0.109"), port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
// This method requests the home page content for the specified server.
private static string SocketSendReceive(string server, int port)
{
string request = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n" + DateTime.Now + "\n" + DateTime.Now+10+"\n";
DateTime t1 = DateTime.Now;
Thread.Sleep(1000);
Random r = new Random();
int randomSeconds = r.Next(100, 101);
DateTime dt = DateTime.Now.AddSeconds(randomSeconds);
request += "\n" + (dt-t1).Seconds;
byte[] bytesSent = Encoding.ASCII.GetBytes(request);
byte[] bytesReceived = new Byte[256];
// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(server, port);
if (s == null)
return ("Connection failed");
// Send request to the server.
s.Send(bytesSent, bytesSent.Length, 0);
Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(bytesSent));
// Receive the server home page content.
int bytes = 0;
string page = "Default HTML page on " + server + ":\r\n";
// The following will block until te page is transmitted.
//do
//{
bytes = s.Receive(bytesReceived);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
// } while (bytes > 0);
Console.WriteLine("接收消息为:" + Encoding.ASCII.GetString(bytesReceived));
s.Close();
return page;
}
public class GoodTasteApple : Decorator
{
public GoodTasteApple(Apple apple) : base(apple)
{
}
public GoodTasteApple(Apple apple) : base(apple)
{
}
public override void Speak()
{
base.Speak();
GoodTasteAppleSpeak();
}
public void GoodTasteAppleSpeak()
{
Console.WriteLine("this is a good taste Apple");
}
}
}
}
public class pathDTO
{
int _i;
public pathDTO(int i)
{
l.Add(i);
}
public List<int> l { get; set; }
}
public class Route
{
public List<pathDTO> route { get; set; }
}
public class Session
{
public Socket ClientSocket { get; set; }
public int MaxConnection { get; private set; }
public string IP; // client ip
public Session(Socket clientSocket)
{
ClientSocket = clientSocket;
IP = GetIPString();
}
private string GetIPString()
{
//throw new NotImplementedException();
string result = ((IPEndPoint)ClientSocket.RemoteEndPoint).Address.ToString();
return result;
}
private object sessionLock = new object();
}
// This example demonstrates a thread-safe method that adds to a
// running total. It cannot be run directly. You can compile it
// as a library, or add the class to a project.
public class ThreadSafe
{
// totalValue contains a running total that can be updated
// by multiple threads. It must be protected from unsynchronized
// access.
private int totalValue = 0;
// The Total property returns the running total.
public int Total
{
get { return totalValue; }
}
// AddToTotal safely adds a value to the running total.
public int AddToTotal(int addend)
{
int initialValue, computedValue;
do
{
// Save the current running total in a local variable.
initialValue = totalValue;
// Add the new value to the running total.
computedValue = initialValue + addend;
// CompareExchange compares totalValue to initialValue. If
// they are not equal, then another thread has updated the
// running total since this loop started. CompareExchange
// does not update totalValue. CompareExchange returns the
// contents of totalValue, which do not equal initialValue,
// so the loop executes again.
} while (initialValue != Interlocked.CompareExchange(
ref totalValue, computedValue, initialValue));
// If no other thread updated the running total, then
// totalValue and initialValue are equal when CompareExchange
// compares them, and computedValue is stored in totalValue.
// CompareExchange returns the value that was in totalValue
// before the update, which is equal to initialValue, so the
// loop ends.
// The function returns computedValue, not totalValue, because
// totalValue could be changed by another thread between
// the time the loop ends and the function returns.
return computedValue;
}
}
}