C# Socket
using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; namespace csocket { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Socket server; Socket client; Socket baglanan_soketimiz; // serverin kabul ettiği, bağlanan soketimiz. (multi için generic list veya dictionary kullanabilirsiniz.) int i = 0; private void button1_Click(object sender, EventArgs e) { Dinle(); } public void Dinle() { try { server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.SendTimeout = -1; server.ReceiveTimeout = -1; server.SendBufferSize = int.MaxValue; server.ReceiveBufferSize = int.MaxValue; server.NoDelay = true; server.Bind(new IPEndPoint(IPAddress.Any, int.Parse(textBox1.Text))); server.Listen(int.MaxValue); server.BeginAccept(new AsyncCallback(Client_Kabul), server); } catch (Exception ex) { MessageBox.Show(ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Warning); Environment.Exit(0); } } public void Client_Kabul(IAsyncResult ar) { Socket listener = (Socket)ar.AsyncState; Socket sock = listener.EndAccept(ar); sock.SendTimeout = -1; sock.ReceiveTimeout = -1; sock.ReceiveBufferSize = int.MaxValue; sock.SendBufferSize = int.MaxValue; sock.NoDelay = true; baglanan_soketimiz = sock; try { new Thread(new ThreadStart(() => { ClientSession inf = new ClientSession(sock, this); })) { IsBackground = true }.Start(); } catch (Exception) { } listener.BeginAccept(new AsyncCallback(Client_Kabul), listener); } public class ClientSession : IDisposable { private MemoryStream memos = null; private byte[] dataByte = new byte[8192]; //1024 * 8 private int blockSize = 8192; private Form1 tmp_form; private Socket tmp; public ClientSession(Socket _client, Form1 frm1) { memos = new MemoryStream(); tmp_form = frm1; tmp = _client; frm1.i = frm1.i + 1; frm1.Text = frm1.Text + " - Yeni Bağlantı " + frm1.i.ToString(); Read(_client); } private async void Read(Socket client) { await Task.Run(async () => { int readed; while (true) { try { readed = client.Receive(dataByte, 0, blockSize, SocketFlags.None); if (readed > 0) { if (memos != null) { memos.Write(dataByte, 0, readed); await UnPacker(client); } } } catch (Exception) { break; } await Task.Delay(1); } }); } private async Task UnPacker(Socket sck) { await Task.Run(async () => { //YEDEK REGEX: <[A-Z]+>\|[0-9]+\|.*?> //string letter = "qwertyuıopğüasdfghjklşizxcvbnmöç1234567890<>|"; Regex regex = new Regex(@"<[A-Z]+>\|[0-9]+\|.*>"); byte[] gecici = memos.ToArray(); byte[][] filebytes = Separate(gecici, Encoding.UTF8.GetBytes("SUFFIX")); for (int k = 0; k < filebytes.Length; k++) { if (!(filebytes[k].Length <= 0)) { try { string ch = Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 1] });// > string f = Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 2] });// F> string o = Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 3] });// OF> string e = Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 4] });// EOF> string ch_ = Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 5] });// <EOF> bool isContainsEof = (ch_ + e + o + f + ch) == "<EOF>"; if (isContainsEof) { List<byte> mytagByte = new List<byte>(); string temp = ""; for (int p = 0; p < filebytes[k].Length; p++) { //if (letter.Contains(Encoding.UTF8.GetString(new byte[1] { filebytes[k][p] }).ToLower())) //{ temp += Encoding.UTF8.GetString(new byte[1] { filebytes[k][p] }); mytagByte.Add(filebytes[k][p]); if (regex.IsMatch(temp)) { break; } //} } string whatsTag = Encoding.UTF8.GetString(mytagByte.ToArray()); MemoryStream tmpMemory = new MemoryStream(); tmpMemory.Write(filebytes[k], 0, filebytes[k].Length); tmpMemory.Write(Encoding.UTF8.GetBytes("SUFFIX"), 0, Encoding.UTF8.GetBytes("SUFFIX").Length); gecici = RemoveBytes(gecici, tmpMemory.ToArray()); memos.Flush(); memos.Close(); memos.Dispose(); // memos = new MemoryStream(); memos.Write(gecici, 0, gecici.Length); tmpMemory.Flush(); tmpMemory.Close(); tmpMemory.Dispose(); filebytes[k] = RemoveBytes(filebytes[k], mytagByte.ToArray()); filebytes[k] = RemoveBytes(filebytes[k], Encoding.UTF8.GetBytes("<EOF>")); await tmp_form.DataProcess(sck, whatsTag, filebytes[k]); } } catch (Exception) { } } } }); } private byte[][] Separate(byte[] source, byte[] separator) { var Parts = new List<byte[]>(); var Index = 0; byte[] Part; for (var I = 0; I < source.Length; ++I) { if (Equals(source, separator, I)) { Part = new byte[I - Index]; Array.Copy(source, Index, Part, 0, Part.Length); Parts.Add(Part); Index = I + separator.Length; I += separator.Length - 1; } } Part = new byte[source.Length - Index]; Array.Copy(source, Index, Part, 0, Part.Length); Parts.Add(Part); return Parts.ToArray(); } private bool Equals(byte[] source, byte[] separator, int index) { for (int i = 0; i < separator.Length; ++i) if (index + i >= source.Length || source[index + i] != separator[i]) return false; return true; } private byte[] RemoveBytes(byte[] input, byte[] pattern) { if (pattern.Length == 0) return input; var result = new List<byte>(); for (int i = 0; i < input.Length; i++) { var patternLeft = i <= input.Length - pattern.Length; if (patternLeft && (!pattern.Where((t, j) => input[i + j] != t).Any())) { i += pattern.Length - 1; } else { result.Add(input[i]); } } return result.ToArray(); } public void CloseSocks() { if (tmp != null) { try { tmp.Close(); } catch (Exception) { } try { tmp.Dispose(); } catch (Exception) { } } try { memos.Flush(); memos.Close(); memos.Dispose(); } catch (Exception) { } try { Dispose(); } catch (Exception) { } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected bool Disposed { get; private set; } protected virtual void Dispose(bool disposing) { Disposed = true; } } public async Task DataProcess(Socket soket2, string tag, byte[] dataBuff) { await Task.Run(() => { try { switch (tag.Split('|')[0]) { case "<RESIM>": Image im = (Image)new ImageConverter().ConvertFrom(dataBuff); pictureBox1.Image = im; break; case "<MESAJ>": textBox2.Text += Encoding.UTF8.GetString(dataBuff) + Environment.NewLine; break; } } catch { } }); } public async Task ClientDataProcess(string tag, byte[] dataBuff) { await Task.Run(() => { try { switch (tag.Split('|')[0]) { case "<RESIM>": Image im = (Image)new ImageConverter().ConvertFrom(dataBuff); pictureBox2.Image = im; break; case "<MESAJ>": textBox7.Text += Encoding.UTF8.GetString(dataBuff) + Environment.NewLine; break; } } catch { } }); } private void button3_Click(object sender, EventArgs e) { Baglanti_Kur(); } public async void Baglanti_Kur() { await Task.Run(() => { try { IPAddress ipadresi = Dns.GetHostAddresses(textBox5.Text)[0]; IPEndPoint endpoint = new IPEndPoint(ipadresi, int.Parse(textBox4.Text)); client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.ReceiveTimeout = -1; client.SendTimeout = -1; client.ReceiveBufferSize = int.MaxValue; client.SendBufferSize = int.MaxValue; client.NoDelay = true; client.Connect(endpoint); label4.Text = "bağlandı."; new ServerSession(client, this); } catch { } }); } public byte[] MyDataPacker(string tag, byte[] message, string extraInfos = "null") { using (MemoryStream ms = new MemoryStream()) { ms.Write(System.Text.Encoding.UTF8.GetBytes($"<{tag}>|{message.Length}|{extraInfos}>"), 0, System.Text.Encoding.UTF8.GetBytes($"<{tag}>|{message.Length}|{extraInfos}>").Length); ms.Write(message, 0, message.Length); ms.Write(System.Text.Encoding.UTF8.GetBytes("<EOF>"), 0, System.Text.Encoding.UTF8.GetBytes("<EOF>").Length); ms.Write(System.Text.Encoding.UTF8.GetBytes("SUFFIX"), 0, System.Text.Encoding.UTF8.GetBytes("SUFFIX").Length); return ms.ToArray(); } } public class ServerSession : IDisposable { private MemoryStream memos = new MemoryStream(); private byte[] dataByte = new byte[8192]; // 1024 * 8 private int blockSize = 8192; Form1 ff; public ServerSession(Socket serverSock, Form1 frm) { ff = frm; Read(serverSock); } private async void Read(Socket server) { await Task.Run(async () => { int readed = default; while (true) { try { readed = server.Receive(dataByte, 0, blockSize, SocketFlags.None); if (readed > 0) { if (memos != null) { memos.Write(dataByte, 0, readed); UnPacker(memos); } } } catch (Exception) { Dispose(); break; } await Task.Delay(1); } }); } private async void UnPacker(MemoryStream ms) { await Task.Run(() => { //string letter = "qwertyuıopğüasdfghjklşizxcvbnmöç1234567890<>|"; Regex regex = new Regex(@"<[A-Z]+>\|[0-9]+\|.*>"); byte[][] filebytes = Separate(ms.ToArray(), System.Text.Encoding.UTF8.GetBytes("SUFFIX")); for (int k = 0; k < filebytes.Length; k++) { if (!(filebytes[k].Length <= 0)) { try { string ch = System.Text.Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 1] });// > string f = System.Text.Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 2] });// F> string o = System.Text.Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 3] });// OF> string e = System.Text.Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 4] });// EOF> string ch_ = System.Text.Encoding.UTF8.GetString(new byte[1] { filebytes[k][filebytes[k].Length - 5] });// <EOF> bool isContainsEof = (ch_ + e + o + f + ch) == "<EOF>"; if (isContainsEof) { List<byte> mytagByte = new List<byte>(); string temp = ""; for (int p = 0; p < filebytes[k].Length; p++) { //if (letter.Contains(Encoding.UTF8.GetString(new byte[1] { filebytes[k][p] }).ToLower())) //{ temp += System.Text.Encoding.UTF8.GetString(new byte[1] { filebytes[k][p] }); mytagByte.Add(filebytes[k][p]); if (regex.IsMatch(temp)) { break; } //} } string whatsTag = System.Text.Encoding.UTF8.GetString(mytagByte.ToArray()); MemoryStream tmpMemory = new MemoryStream(); tmpMemory.Write(filebytes[k], 0, filebytes[k].Length); tmpMemory.Write(System.Text.Encoding.UTF8.GetBytes("SUFFIX"), 0, System.Text.Encoding.UTF8.GetBytes("SUFFIX").Length); ms.Flush(); ms.Close(); ms.Dispose(); ms = new MemoryStream(RemoveBytes(ms.ToArray(), tmpMemory.ToArray())); memos = new MemoryStream(); ms.CopyTo(memos); tmpMemory.Flush(); tmpMemory.Close(); tmpMemory.Dispose(); filebytes[k] = RemoveBytes(filebytes[k], mytagByte.ToArray()); filebytes[k] = RemoveBytes(filebytes[k], System.Text.Encoding.UTF8.GetBytes("<EOF>")); ff.ClientDataProcess(whatsTag, filebytes[k]); } } catch (Exception) { } } } }); } private byte[][] Separate(byte[] source, byte[] separator) { var Parts = new List<byte[]>(); var Index = 0; byte[] Part; for (var I = 0; I < source.Length; ++I) { if (Equals(source, separator, I)) { Part = new byte[I - Index]; Array.Copy(source, Index, Part, 0, Part.Length); Parts.Add(Part); Index = I + separator.Length; I += separator.Length - 1; } } Part = new byte[source.Length - Index]; Array.Copy(source, Index, Part, 0, Part.Length); Parts.Add(Part); return Parts.ToArray(); } private bool Equals(byte[] source, byte[] separator, int index) { for (int i = 0; i < separator.Length; ++i) if (index + i >= source.Length || source[index + i] != separator[i]) return false; return true; } private byte[] RemoveBytes(byte[] input, byte[] pattern) { if (pattern.Length == 0) return input; var result = new List<byte>(); for (int i = 0; i < input.Length; i++) { var patternLeft = i <= input.Length - pattern.Length; if (patternLeft && (!pattern.Where((t, j) => input[i + j] != t).Any())) { i += pattern.Length - 1; } else { result.Add(input[i]); } } return result.ToArray(); } public void Dispose() { Dispose(true); try { GC.SuppressFinalize(this); } catch (Exception) { } } protected bool Disposed { get; private set; } protected virtual void Dispose(bool disposing) { Disposed = true; } } private void button2_Click(object sender, EventArgs e) { byte[] mesaj = MyDataPacker("MESAJ", Encoding.UTF8.GetBytes("Server: " + textBox3.Text)); baglanan_soketimiz.Send(mesaj, mesaj.Length, SocketFlags.None); textBox2.Text += "Ben: " + textBox3.Text + Environment.NewLine; } private void button4_Click(object sender, EventArgs e) { byte[] mesaj = MyDataPacker("MESAJ", Encoding.UTF8.GetBytes("Client: " + textBox6.Text)); client.Send(mesaj, mesaj.Length, SocketFlags.None); textBox7.Text += "Ben: " + textBox6.Text + Environment.NewLine; // servere bağlandığımızda client olarak direkt veri gönderebiliyoruz. } private void button5_Click(object sender, EventArgs e) { using (OpenFileDialog op = new OpenFileDialog()) { op.Title = "Bir resim seçin"; op.Filter = "Resim|*.png;*.jpg"; op.Multiselect = false; if (op.ShowDialog() == DialogResult.OK) { byte[] resim = File.ReadAllBytes(op.FileName); byte[] gidecek_Resim = MyDataPacker("RESIM", resim); baglanan_soketimiz.Send(gidecek_Resim, gidecek_Resim.Length, SocketFlags.None); } } } private void button6_Click(object sender, EventArgs e) { using (OpenFileDialog op = new OpenFileDialog()) { op.Title = "Bir resim seçin"; op.Filter = "Resim|*.png;*.jpg"; op.Multiselect = false; if (op.ShowDialog() == DialogResult.OK) { byte[] resim = File.ReadAllBytes(op.FileName); byte[] gidecek_Resim = MyDataPacker("RESIM", resim); client.Send(gidecek_Resim, gidecek_Resim.Length, SocketFlags.None); } } } } }
Leave a Comment