我无法让我的Sender线程连接到我的Receiver线程。这是我下面的代码(我是套接字编程的新手,所以如果你知道更好的通过套接字发送图像请告诉我):
发件人帖子:
public void SendSS()
{
try
{
while (!mainFrm.ssStop)
{
TcpClient ssTcpClient = new TcpClient();
ssTcpClient.Connect(mainFrm.contactIP, 1500);
if (ssTcpClient.Connected)
{
Image screenShotBMP = GrabScreen();
NetworkStream ns = ssTcpClient.GetStream();
memStream = new MemoryStream();
screenShotBMP.Save(memStream, ImageFormat.Png);
byte[] bytesToSend = memStream.ToArray(); ;
ns.Write(bytesToSend, 0, bytesToSend.Length);
ns.Flush();
screenShotBMP.Dispose();
ns.Close();
memStream.Close();
ssTcpClient.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "frmVoiceChat-SendSS()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
接收者线程:
public void ReceiveSS()
{
try
{
TcpListener ssTcpListener = new TcpListener(IPAddress.Any, 1500);
while (!mainFrm.ssStop)
{
ssTcpListener.Start();
TcpClient tcpReceiver = ssTcpListener.AcceptTcpClient();
//TcpClient tcpReceiver = new TcpClient();
ssTcpListener.AcceptTcpClient();
//tcpReceiver.Connect(mainFrm.contactIP, 1500);
if (tcpReceiver.Connected)
{
labelText("Connected!!!");
//NetworkStream receivedNs = tcpReceiver.GetStream();
NetworkStream receivedNs = new NetworkStream(tcpReceiver.Client);
//ssTcpListener.Server.Receive();
//byte[] imageBytes = new byte[tcpReceiver.ReceiveBufferSize];
//receivedNs.Read(imageBytes, 0, imageBytes.Length);
//MemoryStream receivedMs = new MemoryStream(imageBytes);
//receivedNs.CopyTo(receivedMs);
//Image image = Image.FromStream(receivedNs); // ArgumentException: Parameter is not valid exception here.
pbScreenShare.Image = new Bitmap(receivedNs);
receivedNs.Close();
tcpReceiver.Close();
ssTcpListener.Stop();
//image.Dispose();
//receivedMs.Close();
}
else
{
labelText("Not Connected!!!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "frmVoiceChat-ReceiveSS()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 0 :(得分:3)
您拨打AcceptTcpClient()
两次。第二个调用将等待连接并阻止其余代码执行。请清理您的代码。