C# 채팅질문! (내공200)
-
게시물 수정 , 삭제는 로그인 필요
만약에 해서 안되면 채택은 못해드릴것같아요 ㅠ
일단 문제점은 이겁니다 벌써 지식인 4번째 글이에요 ㅠㅠ
만약에 123를 치면 출력이 잘되요. 123으로
하지만 여기서 2를 치면 223으로 출력이 되네요 ㅠㅠ
왜그럴가요..
[ 기본화면 입니다 ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_61/1582107208242khnQw_PNG/%C4%B8%C3%B3_2020_02_19_19_09_19_238.png)
[ 여기서 123을 치면 ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_134/1582107208941DYGng_PNG/%C4%B8%C3%B3_2020_02_19_19_09_23_607.png)
[ 잘출력이 되는모습을 볼수 있죵 ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_83/1582107209426mQjyv_PNG/%C4%B8%C3%B3_2020_02_19_19_09_26_995.png)
[ 하지만 전송후 2를 친다면? ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_37/1582107211282V72pE_PNG/%C4%B8%C3%B3_2020_02_19_19_09_40_472.png)
[ 이런식으로 223이 됩니다 ㅠㅠ ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_3/15821072118793Vfpk_PNG/%C4%B8%C3%B3_2020_02_19_19_09_43_498.png)
제발 알려주세요.. 제대로된 답변하나 달리지 않앗어요 ㅠㅠ 진짜 해결만 해주신다면..
진짜 이거 채팅때문에 지식인만 4번올렷어요 ㅠㅠ 부탁드려요.. 꼭 해결하고 싶네요 ㅠ
제가 잘못 설명한가 싶어서 이렇게 자세히 알려드려요 ㅠㅠ
제가 원하는건 단지 "안녕하세요" 쳤을때
서버로그에도 "안녕하세요"가 뜨는거구용 ㅠㅠ
그리고 "안녕하세요"를 전송한후 "하이" 라고 보내면 "하이하세요"라고 출력이 되지않고 "하이"로만 출력이 되게끔 하고싶어요..
진짜 부탁드리구요.. 제가 초보라서 쉽게 쉽게 설명해 주셨으면 좋겠어요.ㅜㅜ
저는 자세한 설명보단 코드로 주셨으면 좋겠습니다..
클라이언트쪽 코드
using System;
using System.Linq;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace 피리톡V1._0
{
public partial class MainForm : MetroFramework.Forms.MetroForm
{
#region MainForm
public static string Client_IP
{
get
{
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
string ClientIP = string.Empty;
for (int i = 0; i < host.AddressList.Length; i++)
{
if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
ClientIP = host.AddressList[i].ToString();
}
}
return ClientIP;
}
}
MySqlConnection connection = new MySqlConnection("Server=220.78.193.111; Database=mydb; Uid=root; Pwd=tngh1004;");
public MySqlCommand MySqlCommand { get; set; }
public MainForm()
{
InitializeComponent();
connection.Open();
String sql = "SELECT NICKNAME FROM user_info WHERE ip = " + "'" + Client_IP + "';";
MySqlCommand cmd = new MySqlCommand(sql, connection);
MySqlDataReader rb = cmd.ExecuteReader();
try
{
if (rb.Read())
{
string Arr = rb["NICKNAME"].ToString();
label1.Text = Arr + "님, 피리툴에 오신것을 환영합니다."; ;
connection.Close();
}
else
{
MessageBox.Show("UI를 불러오던 중 오류가 발생하였습니다.");
connection.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
connection.Close();
Close();
}
}
#endregion
private Socket m_ClientSocket = null;
#region MainForm_Load
private void MainForm_Load(object sender, EventArgs e)
{
m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint remoteIP = new IPEndPoint(IPAddress.Parse("220.78.193.111"), 10000);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = remoteIP;
m_ClientSocket.ConnectAsync(args);
}
#endregion
#region button1_Click method
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = Encoding.Unicode.GetBytes(textBox1.Text);
args.SetBuffer(szData, 0, szData.Length);
m_ClientSocket.SendAsync(args);
textBox1.Text = "";
textBox1.Focus();
}
}
private void btnEnter_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = new byte[1024];
Array.Clear(szData, 0, szData.Length);
szData = Encoding.Unicode.GetBytes(textBox1.Text);
args.SetBuffer(szData, 0, szData.Length);
m_ClientSocket.SendAsync(args);
textBox1.Text = "";
textBox1.Focus();
}
}
#endregion
#region Dispose
protected override void Dispose(bool disposing)
{
if (m_ClientSocket.Connected)
m_ClientSocket.Disconnect(false);
m_ClientSocket.Dispose();
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
}
}
서버쪽 코드
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Diagnostics;
using System.Xml.Linq;
namespace 피리톡_서버_실행기_V1._0
{
public partial class MainForm : Form
{
#region MainForm
public MainForm()
{
InitializeComponent();
}
#endregion
#region MainForm_Load
private Socket m_ServerSocket;
private List<Socket> m_ClientSocket;
private byte[] szData;
private void MainForm_Load(object sender, EventArgs e)
{
m_ClientSocket = new List<Socket>();
m_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("220.78.193.111"), 10000);
m_ServerSocket.Bind(ipep);
m_ServerSocket.Listen(20);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
m_ServerSocket.AcceptAsync(args);
}
#endregion
#region Accept_Completed
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = e.AcceptSocket;
m_ClientSocket.Add(ClientSocket);
//접속한 클라이언수 보이기
//label1.Text = m_ClientSocket.Count.ToString();
try
{
if (m_ClientSocket != null)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = new byte[1024];
Array.Clear(szData, 0, szData.Length);
args.SetBuffer(szData, 0, szData.Length);
args.UserToken = m_ClientSocket;
args.Completed += new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
ClientSocket.ReceiveAsync(args);
}
e.AcceptSocket = null;
m_ServerSocket.AcceptAsync(e);
}
catch (SocketException se)
{
Trace.WriteLine(string.Format("SocketException : {0}", se.Message));
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Exception : {0}", ex.Message));
}
}
#endregion
#region Receive_Completed
private void Receive_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = sender as Socket;
if (ClientSocket.Connected && e.BytesTransferred > 0)
{
byte[] szData = e.Buffer;
string sData = Encoding.Unicode.GetString(szData);
sData = sData.Replace("\0", "").Trim();
SetText(sData);
e.SetBuffer(szData, 0, 1024);
ClientSocket.ReceiveAsync(e);
}
else
{
ClientSocket.Disconnect(false);
ClientSocket.Dispose();
m_ClientSocket.Remove(ClientSocket);
}
//접속한 클라이언수 보이기
//label1.Text = m_ClientSocket.Count.ToString();
}
#endregion
#region SetText
private delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (richTextBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
if (richTextBox1.TextLength > 0)
{
richTextBox1.AppendText("\n");
}
richTextBox1.AppendText(text);
richTextBox1.ScrollToCaret();
}
}
#endregion
#region Dispose
protected override void Dispose(bool disposing)
{
foreach (Socket pBuffer in m_ClientSocket)
{
if (pBuffer.Connected)
pBuffer.Disconnect(false);
pBuffer.Dispose();
}
m_ServerSocket.Dispose();
if (disposing && components != null)
components.Dispose();
base.Dispose(disposing);
}
#endregion</socketasynceventargs></socketasynceventargs></socket></socket>
}
}
1대 1로 알려주실수 있으면 디스코드 : 피리#8800 이나, 카카오톡 : korpiho 로 부탁드립니다..
일단 문제점은 이겁니다 벌써 지식인 4번째 글이에요 ㅠㅠ
만약에 123를 치면 출력이 잘되요. 123으로
하지만 여기서 2를 치면 223으로 출력이 되네요 ㅠㅠ
왜그럴가요..
[ 기본화면 입니다 ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_61/1582107208242khnQw_PNG/%C4%B8%C3%B3_2020_02_19_19_09_19_238.png)
[ 여기서 123을 치면 ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_134/1582107208941DYGng_PNG/%C4%B8%C3%B3_2020_02_19_19_09_23_607.png)
[ 잘출력이 되는모습을 볼수 있죵 ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_83/1582107209426mQjyv_PNG/%C4%B8%C3%B3_2020_02_19_19_09_26_995.png)
[ 하지만 전송후 2를 친다면? ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_37/1582107211282V72pE_PNG/%C4%B8%C3%B3_2020_02_19_19_09_40_472.png)
[ 이런식으로 223이 됩니다 ㅠㅠ ]
![](https://img-api.cboard.net/img_n.php?image_url=https://kin-phinf.pstatic.net/20200219_3/15821072118793Vfpk_PNG/%C4%B8%C3%B3_2020_02_19_19_09_43_498.png)
제발 알려주세요.. 제대로된 답변하나 달리지 않앗어요 ㅠㅠ 진짜 해결만 해주신다면..
진짜 이거 채팅때문에 지식인만 4번올렷어요 ㅠㅠ 부탁드려요.. 꼭 해결하고 싶네요 ㅠ
제가 잘못 설명한가 싶어서 이렇게 자세히 알려드려요 ㅠㅠ
제가 원하는건 단지 "안녕하세요" 쳤을때
서버로그에도 "안녕하세요"가 뜨는거구용 ㅠㅠ
그리고 "안녕하세요"를 전송한후 "하이" 라고 보내면 "하이하세요"라고 출력이 되지않고 "하이"로만 출력이 되게끔 하고싶어요..
진짜 부탁드리구요.. 제가 초보라서 쉽게 쉽게 설명해 주셨으면 좋겠어요.ㅜㅜ
저는 자세한 설명보단 코드로 주셨으면 좋겠습니다..
클라이언트쪽 코드
using System;
using System.Linq;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace 피리톡V1._0
{
public partial class MainForm : MetroFramework.Forms.MetroForm
{
#region MainForm
public static string Client_IP
{
get
{
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
string ClientIP = string.Empty;
for (int i = 0; i < host.AddressList.Length; i++)
{
if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
ClientIP = host.AddressList[i].ToString();
}
}
return ClientIP;
}
}
MySqlConnection connection = new MySqlConnection("Server=220.78.193.111; Database=mydb; Uid=root; Pwd=tngh1004;");
public MySqlCommand MySqlCommand { get; set; }
public MainForm()
{
InitializeComponent();
connection.Open();
String sql = "SELECT NICKNAME FROM user_info WHERE ip = " + "'" + Client_IP + "';";
MySqlCommand cmd = new MySqlCommand(sql, connection);
MySqlDataReader rb = cmd.ExecuteReader();
try
{
if (rb.Read())
{
string Arr = rb["NICKNAME"].ToString();
label1.Text = Arr + "님, 피리툴에 오신것을 환영합니다."; ;
connection.Close();
}
else
{
MessageBox.Show("UI를 불러오던 중 오류가 발생하였습니다.");
connection.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
connection.Close();
Close();
}
}
#endregion
private Socket m_ClientSocket = null;
#region MainForm_Load
private void MainForm_Load(object sender, EventArgs e)
{
m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint remoteIP = new IPEndPoint(IPAddress.Parse("220.78.193.111"), 10000);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = remoteIP;
m_ClientSocket.ConnectAsync(args);
}
#endregion
#region button1_Click method
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = Encoding.Unicode.GetBytes(textBox1.Text);
args.SetBuffer(szData, 0, szData.Length);
m_ClientSocket.SendAsync(args);
textBox1.Text = "";
textBox1.Focus();
}
}
private void btnEnter_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = new byte[1024];
Array.Clear(szData, 0, szData.Length);
szData = Encoding.Unicode.GetBytes(textBox1.Text);
args.SetBuffer(szData, 0, szData.Length);
m_ClientSocket.SendAsync(args);
textBox1.Text = "";
textBox1.Focus();
}
}
#endregion
#region Dispose
protected override void Dispose(bool disposing)
{
if (m_ClientSocket.Connected)
m_ClientSocket.Disconnect(false);
m_ClientSocket.Dispose();
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
}
}
서버쪽 코드
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Diagnostics;
using System.Xml.Linq;
namespace 피리톡_서버_실행기_V1._0
{
public partial class MainForm : Form
{
#region MainForm
public MainForm()
{
InitializeComponent();
}
#endregion
#region MainForm_Load
private Socket m_ServerSocket;
private List<Socket> m_ClientSocket;
private byte[] szData;
private void MainForm_Load(object sender, EventArgs e)
{
m_ClientSocket = new List<Socket>();
m_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("220.78.193.111"), 10000);
m_ServerSocket.Bind(ipep);
m_ServerSocket.Listen(20);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
m_ServerSocket.AcceptAsync(args);
}
#endregion
#region Accept_Completed
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = e.AcceptSocket;
m_ClientSocket.Add(ClientSocket);
//접속한 클라이언수 보이기
//label1.Text = m_ClientSocket.Count.ToString();
try
{
if (m_ClientSocket != null)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = new byte[1024];
Array.Clear(szData, 0, szData.Length);
args.SetBuffer(szData, 0, szData.Length);
args.UserToken = m_ClientSocket;
args.Completed += new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
ClientSocket.ReceiveAsync(args);
}
e.AcceptSocket = null;
m_ServerSocket.AcceptAsync(e);
}
catch (SocketException se)
{
Trace.WriteLine(string.Format("SocketException : {0}", se.Message));
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Exception : {0}", ex.Message));
}
}
#endregion
#region Receive_Completed
private void Receive_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = sender as Socket;
if (ClientSocket.Connected && e.BytesTransferred > 0)
{
byte[] szData = e.Buffer;
string sData = Encoding.Unicode.GetString(szData);
sData = sData.Replace("\0", "").Trim();
SetText(sData);
e.SetBuffer(szData, 0, 1024);
ClientSocket.ReceiveAsync(e);
}
else
{
ClientSocket.Disconnect(false);
ClientSocket.Dispose();
m_ClientSocket.Remove(ClientSocket);
}
//접속한 클라이언수 보이기
//label1.Text = m_ClientSocket.Count.ToString();
}
#endregion
#region SetText
private delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (richTextBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
if (richTextBox1.TextLength > 0)
{
richTextBox1.AppendText("\n");
}
richTextBox1.AppendText(text);
richTextBox1.ScrollToCaret();
}
}
#endregion
#region Dispose
protected override void Dispose(bool disposing)
{
foreach (Socket pBuffer in m_ClientSocket)
{
if (pBuffer.Connected)
pBuffer.Disconnect(false);
pBuffer.Dispose();
}
m_ServerSocket.Dispose();
if (disposing && components != null)
components.Dispose();
base.Dispose(disposing);
}
#endregion</socketasynceventargs></socketasynceventargs></socket></socket>
}
}
1대 1로 알려주실수 있으면 디스코드 : 피리#8800 이나, 카카오톡 : korpiho 로 부탁드립니다..