일부 주제에서 내 대답을 찾을 수 없습니다. 클라이언트 / 서버 코드가 있습니다. 별도의 프로그램에 클라이언트 측과 서버 측이 있습니다. 이것은 클라이언트 측입니다.
try
{
byte[] bytes = new byte[1024];
string text = "";
text = uitbtextmsg.Text;
byte[] msg = Encoding.ASCII.GetBytes(text);
int bytesSent = User.Send(msg);
int bytesRec = User.Receive(bytes);
uirtbmsg.Text = uirtbmsg.Text + '\n' + " " + text;
}
catch (Exception E)
{
MessageBox.Show(E.ToString());
}
이것은 내가 서버에 연결되어 있고 그 소켓과 채팅하고 싶을 때입니다. 이것은 내 연결입니다.
byte[] bytes = new byte[1024];
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[2];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
Socket User = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
User.Connect(remoteEP);
그리고 이것은 서버 측입니다.
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[2];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10000);
while (true)
{
Socket handler = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
TextRecieved = data;
Thread textbox = new Thread(new ThreadStart(WriteInReachTextBox));
textbox.Start();
break;
}
//uirtbreport.Text = data;
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
클라이언트가 처음 서버에 메시지를 보낼 때이 절차는 괜찮습니다! 그러나 다른 메시지를 보내면 예외가 발생합니다.
System.Net.Socket.SocketException (0x80004005) : 시스템의 System.Net.Sockets.Socket.Receive (Byte [] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)에서 호스트 컴퓨터의 소프트웨어에 의해 설정된 연결이 중단되었습니다. .Net.Sockets.Socket.Receive (Byte [] buffer) \ r \ n at Client.Form1.uibtnsendmsg_Click (Object sender, EventArgs e) in ...
아마도 당신이 while 루프를 깨고 있기 때문일 것입니다 (내 의견을보십시오)
while (true)
{
Socket handler = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
TextRecieved = data;
Thread textbox = new Thread(new ThreadStart(WriteInReachTextBox));
textbox.Start();
// -----------> HERE!!!!!!
break;
}
//uirtbreport.Text = data;
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
왜 '깨진'루프 내에 스레드를 생성합니까?
또한 이것이 스트리밍 소켓이라는 것을 잊지 마십시오. 이는 '패킷'을 하나의 버퍼로 보내거나 여러 '패킷'으로 분할 할 수 있음을 의미합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다