C#中socket通信问题
发布网友
发布时间:2023-11-14 03:36
我来回答
共4个回答
热心网友
时间:2024-12-05 11:13
下面的代码只是服务端的,客户端的类似了哈!!
/// <summary>
/// 开启监听线程方法
/// </summary>
/// <param name="port">端口</param>
private void ServerThread(object port)
{
try
{
IPEndPoint point = new IPEndPoint(IPAddress.Any, (int)port);//创建socket端点
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(point);
serverSocket.Listen(10);
while (true)
{
try
{
Socket ClientSocket = serverSocket.Accept();
IPEndPoint clientep = (IPEndPoint)ClientSocket.RemoteEndPoint;
new Thread(ClientThread).Start(ClientSocket);
}
catch (Exception ex)
{
serverSocket.Close();
MessageBox.Show(ex.ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 接收数据线程方法
/// </summary>
/// <param name="socket">目标客户端</param>
private void ClientThread(object socket)
{
Socket Client = socket as Socket;
try
{
int BufferLength = 1024;
while (true)
{
if ((BufferLength = Client.Available) != 0)
{
byte[] buffer = new byte[BufferLength];
Client.Receive(buffer, 0, BufferLength, SocketFlags.None);// 接收
//doSomeThing......
}
Thread.Sleep(1);
}
}
catch (Exception ex)
{
if (!ex.GetType().Equals(typeof(ObjectDisposedException)))
{
Client.Close();
Client.Dispose();
}
}
}
调用
private void button1_Click(object sender, EventArgs e)
{
new Thread(ServerThread).Start((12345);
button1.Enabled = false;
}
热心网友
时间:2024-12-05 11:14
您好,这样的:
TCP是面向连接的,服务端接收到连接(Socket client = server.Accept() )后,表示连接已经建立好,就可以相互通讯了。服务端用Accept到的client发送消息就行了,客户端不需要再Listen,直接Receive消息就行了(用你建立连接的Socket接收)。客户端发完消息不要关闭掉,用它来接收服务端的消息。追问给点代码实例看看,谢谢了
热心网友
时间:2024-12-05 11:14
你需要一个线程,完成接收操作追问我也觉得,可是线程也刚学会不熟,求个小实例
热心网友
时间:2024-12-05 11:15
要不停的监听追问能具体点么