|
如下的服务端与客户端代码,为何客户端按钮要点击 2 次,才能发送信息,如何修改代码才能使之正常
/////////////////////////////////////////
服务端
private void button_Accept_Click(object sender, EventArgs e)
{
MyInitSocket();
}
private void MyInitSocket()
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string strHostName = Dns.GetHostName();
IPHostEntry myIPHostEntry = Dns.GetHostEntry(strHostName);
IPAddress myIPAddress = myIPHostEntry.AddressList[1];
int port = 9999;
IPEndPoint localEP = new IPEndPoint(myIPAddress, port);
mySocket.Bind(localEP);
mySocket.Listen(5);
ParameterizedThreadStart ptsAccept = new ParameterizedThreadStart(MyAcceptThreadFunc);
Thread MyAcceptThread = new Thread(ptsAccept);
MyAcceptThread.Start();
}
private void MyAcceptThreadFunc(object obj)
{
while (true)
{
Socket myAcceptSocket = mySocket.Accept();
ParameterizedThreadStart ptsAnswer = new ParameterizedThreadStart(MyAnswerThreadFunc);
Thread MyAnswerThread = new Thread(ptsAnswer);
MyAnswerThread.Start(myAcceptSocket);
}
}
private void MyAnswerThreadFunc(object obj)
{
Socket myAnswerSocket = obj as Socket;
NetworkStream ns = new NetworkStream(myAnswerSocket);
while(true)
{
byte[] bufferTemp = new byte[512];
byte[] bufferRecv = new byte[512];
int nReadAlready = ns.Read(bufferRecv, 0, 512);
//假设现在读取到的数据大于512字节,那么一定读满512个字节
do
{
bufferTemp = bufferRecv;
nReadAlready = ns.Read(bufferRecv, 0, 512);
bufferTemp.Concat(bufferRecv);//不知道内存是否够大
} while (nReadAlready == 512);
string strReadAlready = Encoding.Default.GetString(bufferTemp);
//byte[] datasize = new byte[4];
//ns.Read(datasize, 0, 4);
//int size = BitConverter.ToInt32(datasize, 0);
//byte[] message = new byte[size];
//int dataleft = size;
//int start = 0;
//while(dataleft>0)
//{
// int recv = ns.Read(message, start, dataleft);
// start += recv;
// dataleft -= recv;
//}
//string strReadAlready = Encoding.Default.GetString(message);
MyShowText(strReadAlready);
}
}
////////////////////////////////////////////////////////////////////////////////////
客户端
Socket mySocket;
private void MyConnectServer()
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress myIp = IPAddress.Parse("192.168.0.100");
int port = 9999;
mySocket.Connect(myIp, port);
if(mySocket.Connected)
{
string strConnectInfo = mySocket.RemoteEndPoint.ToString();
label_status.Text = "已连接" + strConnectInfo;
}
}
//发送信息的按钮事件
private void button_Send_Click(object sender, EventArgs e)
{
string strSend = textBox_Send.Text;
byte[] btSend = Encoding.Default.GetBytes(strSend);
NetworkStream ns = new NetworkStream(mySocket);
ns.Write(btSend, 0, btSend.Length);
}
private void button_Connect_Click(object sender, EventArgs e)
{
MyConnectServer();
}
|
|