using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SendImage
{
public partial class Form1 : Form
{
Socket sListener = null;
List<Socket> clientList = new List<Socket>();
Thread thread = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dia = new OpenFileDialog();
dia.Multiselect = false;
dia.Filter = "jpg files|*.jpg";
if (dia.ShowDialog() == DialogResult.OK)
{
this.pictureBox1.ImageLocation = dia.FileName;
if (pictureBox1.InvokeRequired)
{
pictureBox1.BeginInvoke(new Action(() => this.pictureBox1.ImageLocation = dia.FileName));
}
else
{
this.pictureBox1.ImageLocation = dia.FileName;
}
foreach (var item in clientList)
{
Byte[] _data = ImageToByteArray(this.pictureBox1.Image);
item.Send(BitConverter.GetBytes(_data.Length));
item.Send(_data);
}
}
}
/// <summary>
/// 이미지를 바이트로
/// https://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public byte[] ImageToByteArray(System.Drawing.Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
private void Form1_Load(object sender, EventArgs e)
{
sListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 8081);
sListener.Bind(ipEndPoint);
sListener.Listen(20);
thread = new Thread(() => {
while (true)
{
Socket sClient = sListener.Accept();
IPEndPoint ip = (IPEndPoint)sClient.RemoteEndPoint;
Console.WriteLine("주소 {0}에서 접속", ip.Address);
clientList.Add(sClient);
}
});
thread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
sListener.Close();
}
}
}