amespace MultiChatServer {
public partial class ChatForm : Form {
delegate void AppendTextDelegate(Control ctrl, string s);
AppendTextDelegate _textAppender;
Socket mainSock;
IPAddress thisAddress;
public ChatForm() {
InitializeComponent();
mainSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
_textAppender = new AppendTextDelegate(AppendText);
DataTable table = new DataTable();
table.Columns.Add("");
table.Columns.Add("Number", typeof(int));
table.Columns.Add("Data", typeof(float));
table.Columns.Add("");
table.Rows.Add("", "1", "99.5", "");
table.Rows.Add("", "2", "24.2", "");
table.Rows.Add("", "3", "53.2", "");
dataGridView1.DataSource = table;
}//선언
void AppendText(Control ctrl, string s) {
if (ctrl.InvokeRequired) ctrl.Invoke(_textAppender, ctrl, s);
else {
string source = ctrl.Text;
ctrl.Text = source + Environment.NewLine + s;
}
}
void OnFormLoaded(object sender, EventArgs e) {
IPHostEntry he = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress addr in he.AddressList) {
if (addr.AddressFamily == AddressFamily.InterNetwork) {
thisAddress = addr;
break;
}
}
if (thisAddress == null)
thisAddress = IPAddress.Loopback;
txtAddress.Text = thisAddress.ToString();
}
void BeginStartServer(object sender, EventArgs e) {
int port;
if (!int.TryParse(txtPort.Text, out port)) {
MsgBoxHelper.Error("포트 번호가 잘못 입력되었거나 입력되지 않았습니다.");
txtPort.Focus();
txtPort.SelectAll();
return;
}
IPEndPoint serverEP = new IPEndPoint(thisAddress, port);
mainSock.Bind(serverEP);
mainSock.Listen(10);
mainSock.BeginAccept(AcceptCallback, null);
}
List<Socket> connectedClients = new List<Socket>();
void AcceptCallback(IAsyncResult ar) {
Socket client = mainSock.EndAccept(ar);
mainSock.BeginAccept(AcceptCallback, null);
AsyncObject obj = new AsyncObject(4096);
obj.WorkingSocket = client;
connectedClients.Add(client);
AppendText(txtHistory, string.Format("사용자 (@ {0})가 연결되었습니다.", client.RemoteEndPoint));
client.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj);
}
void DataReceived(IAsyncResult ar) {
AsyncObject obj = (AsyncObject)ar.AsyncState;
//예외처리 구문 (튕김방지)
string text = Encoding.UTF8.GetString(obj.Buffer);
string[] tokens = text.Split(' ');
string ip = tokens[0];
string msg = tokens[0];
AppendText(txtHistory, string.Format("[받음]{0}: {1}", ip, msg));
for (int i = connectedClients.Count - 1; i >= 0; i--) {
Socket socket = connectedClients[i];
if (socket != obj.WorkingSocket) {
try { socket.Send(obj.Buffer); }
catch {
try { socket.Dispose(); } catch { }
connectedClients.RemoveAt(i);
}
}
}
try
{
int received = obj.WorkingSocket.EndReceive(ar);
}
catch (Exception e)
{
string Message = "서버가 끊어졌습니다" + e.Message;
MessageBox.Show(Message);
return;
}
obj.ClearBuffer();
obj.WorkingSocket.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj);
}
void OnSendData(object sender, EventArgs e) {
if (!mainSock.IsBound) {
MsgBoxHelper.Warn("서버오프라인 상태");
return;
}
string tts = txtTTS.Text.Trim();
if (string.IsNullOrEmpty(tts)) {
MsgBoxHelper.Warn("텍스트가 입력되지 않았습니다!");
txtTTS.Focus();
return;
}
byte[] bDts = Encoding.UTF8.GetBytes(thisAddress.ToString() + '\x01' + tts);
for (int i = connectedClients.Count - 1; i >= 0; i--) {
Socket socket = connectedClients[i];
try { socket.Send(bDts); } catch {
try { socket.Dispose(); } catch { }
connectedClients.RemoveAt(i);
}
}
AppendText(txtHistory, string.Format("[보냄]{0}: {1}", thisAddress.ToString(), tts));
txtTTS.Clear();
}
private void lblPort_Click(object sender, EventArgs e)
{
}
private void txtHistory_TextChanged(object sender, EventArgs e)
{
}
private void lblAddress_Click(object sender, EventArgs e)
{
}
private void tblMainLayout_Paint(object sender, PaintEventArgs e)
{
}
현재 제가 c#으로 tcp/ip 송수신프로그램을 만들어서 짜놓고 실행까지 구현을 해놓은 코드입니다.
다름이아니라 여기서좀더 나아가 옆에 데이타그리드를 통해 표를만들어
클라이언트 쪽에서 예를들어 [ 1, 99.9% ]
이런식으로 텍스트를 전송하게되면 조건문으로 걸어서 그리드쪽으로자동기입이되도록하고싶은데요..
어느부분에서 어떤함수를대략적으로 추가해야 그리드쪽으로 넘어가는지를 도통모르겠습니다..
조건문은 하다보면 될거같은데 넘어가도록 하는 코드를 어디에무엇을추가해야하는지모르겠어요...
[최초 등록일: ]
[최종 수정일: 9/6/2022]