본문 바로가기
Winform

.net socket chatting sample (2) SocketCommon

by 캡틴노랑이 2021. 4. 15.
반응형

Server Source

 

SocketCommon Project

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace SocketCommon
{
    public class AllowAllAssemblyVersionsDeserializationBinder : System.Runtime.Serialization.SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            Type typeToDeserialize = null;
            String currentAssembly = Assembly.GetExecutingAssembly().FullName;
            assemblyName = currentAssembly;
            typeToDeserialize = Type.GetType(string.Format("{0},{1}", typeName, assemblyName));
            return typeToDeserialize;
        }
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Collections.Generic;
using System.Text;
 
namespace SocketCommon
{
    public static class DictionaryExtention
    {
        public static Dictionary<string, string> InsertAtFirst(this Dictionary<string, string> original, string insertAtFirstKey, string insertAtFirstValue, int position)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            int i = 0;
 
            foreach (KeyValuePair<string, string> pair in original)
            {
                if (i == position)
                    dic.Add(insertAtFirstKey, insertAtFirstValue);
 
                dic.Add(pair.Key, pair.Value);
 
                i++;
            }
 
            return dic;
        }
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
 
namespace SocketCommon
{
    [Serializable]
    public class PacketData
    {
        public PacketType packetType { get; set; }
        public string SenderID { get; set; }
        public string ReceiverID { get; set; }
        public string stringData { get; set; }
        public Dictionary<string, string> UsersList { get; set; }
 
        public static byte[] Serialize(Object data)
        {
            try
            {
                MemoryStream ms = new MemoryStream(1024 * 2); // packet size will be maximum 4k
                //MemoryStream ms = new MemoryStream(1024); // packet size will be maximum 4k
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, data);
                return ms.ToArray();
            }
            catch (Exception e)
            {
                return null;
            }
        }
 
        public static Object Deserialize(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream(1024 * 2);
                //MemoryStream ms = new MemoryStream(1024);
                ms.Write(data, 0, data.Length);
 
                ms.Position = 0;
                BinaryFormatter bf = new BinaryFormatter();
                bf.Binder = new AllowAllAssemblyVersionsDeserializationBinder();
                Object obj = bf.Deserialize(ms);
                ms.Close();
                return obj;
            }
            catch(Exception e)
            {
                return null;
            }
        }
 
        public static byte[] JsonSerialize(Object data)
        {
            try
            {
                MemoryStream ms = new MemoryStream(1024); // packet size will be maximum 4k               
                BinaryFormatter bf = new BinaryFormatter();
                string msg = JsonCreate((PacketData)data);
 
                bf.Serialize(ms, msg);
                return ms.ToArray();
            }
            catch (Exception e)
            {
                return null;
            }
        }
 
        public static string JsonCreate(PacketData data)
        {
            var json = new JObject();
 
            json.Add("packetType", data.packetType.ToString());
            json.Add("SenderID", data.SenderID);
            json.Add("ReceiverID", data.ReceiverID);
            json.Add("stringData", data.stringData);
 
            var jarr = new JArray();
            if (data.UsersList != null)
            {
                 
                foreach (var dic in data.UsersList)
                {
                    var j = new JObject();
                    j.Add("Key", dic.Key);
                    j.Add("Value", dic.Value);
                    jarr.Add(j);
                }
                json.Add("UsersList", jarr); //JObject에 추가 할 때는 이렇게 해야됨.
            }
            return json.ToString();
        }
 
        public static Object JsonDeserialize(byte[] data)
        {
            try
            {               
                MemoryStream ms = new MemoryStream(1024);
                ms.Write(data, 0, data.Length);
 
                ms.Position = 0;
                BinaryFormatter bf = new BinaryFormatter();
                bf.Binder = new AllowAllAssemblyVersionsDeserializationBinder();
                Object obj = bf.Deserialize(ms);
                ms.Close();
 
                Object toPacketData = PacketDataCreate((string)obj);
                                
                return toPacketData;
            }
            catch (Exception e)
            {
                return null;
            }
        }
 
        public static PacketData PacketDataCreate(string data)
        {
            PacketData pd = new PacketData();
            pd.UsersList = new Dictionary<string, string>();
            JObject json = new JObject();
             
            try
            {
                if(data != "")
                {
                    json = JObject.Parse(data);
                    pd.packetType = ChangePackageType(json["packetType"].ToString());
                    pd.SenderID = json["SenderID"].ToString();
                    pd.ReceiverID = json["ReceiverID"].ToString();
                    pd.stringData = json["stringData"].ToString();
 
                    foreach(var d in json["UsersList"])
                        pd.UsersList.Add(d["Key"].ToString(), d["Value"].ToString());                   
                }
 
                return pd;
            }
            catch (Exception e)
            {
                return pd;
            }
        }
 
        public static PacketType ChangePackageType(string packageType)
        {
            PacketType pt;
            pt = PacketType.TextData;
 
            switch (packageType)
            {
                case "TextData":
                    pt = PacketType.TextData;
                    break;
                case "FileData":
                    pt = PacketType.FileData;
                    break;
                case "SysMessage":
                    pt = PacketType.SysMessage;
                    break;
                case "UsersInfo":
                    pt = PacketType.UsersInfo;
                    break;
                case "Disconnect":
                    pt = PacketType.Disconnect;
                    break;
            }
            return pt;
        }                            
                                       
    }
}

1
2
3
<code>
 
</code>

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace SocketCommon
{
    public enum PacketType
    {
 
        TextData            //텍스트
        , FileData          //파일
        , SysMessage        //시스템 메세지
        , UsersInfo         //사용자 정보 요청
        , Disconnect        //서버가 접속 끓을 때.
 
 
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
 
namespace SocketCommon
{
    public static class SocketExtention
    {
        public static bool IsConnected(this Socket socket)
        {
            try
            {
                return !((socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0) || !socket.Connected);
            }
            catch (SocketException) { return false; }
        }
    }
}

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
 
namespace SocketCommon
{
    public class StateObject
    {
        public Socket workSocket = null;
        //public const int BufferSize = 1024 * 2;   //class
        public const int BufferSize = 1024;         //json
        public byte[] buffer = new byte[BufferSize];
        public StringBuilder sb = new StringBuilder();
        public string userID = "";
    }
}

반응형

댓글