using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e)
{
IPAddress ip = IPAddress.Parse(textBox1.Text);
IPEndPoint point = new IPEndPoint(ip, int.Parse(textBox2.Text));
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Bind(point);
socket.Listen(20);
ShowMsg("开始监听");
Thread thread = new Thread(AcceptInfo);
thread.IsBackground = true;
thread.Start(socket);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
private Socket client;
void AcceptInfo(object a) {
Socket socket = a as Socket;
while (true)
{
try
{
Socket tSocket = socket.Accept();
string point = tSocket.RemoteEndPoint.ToString();
ShowMsg(point + "连接成功!");
cboIpPort.Items.Add(point);
dic.Add(point, tSocket);
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start(tSocket);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
break;
}
}
}
void ReceiveMsg(object a) {
Socket client = a as Socket;
while (true)
{
try {
byte[] buffer = new byte[1024 * 1024];
int n = client.Receive(buffer);
string words = Encoding.UTF8.GetString(buffer, 0, n);
ShowMsg(client.RemoteEndPoint.ToString() + ":" + words);
}
catch(Exception ex){
ShowMsg(ex.Message);
break;
}
}
}
void ShowMsg(string msg){
txtLog.AppendText(msg+"\r\n");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
try{
ShowMsg(txtMsg.Text);
string ip=cboIpPort.Text;
byte [] buffer=Encoding.UTF8.GetBytes(txtMsg.Text);
dic[ip].Send(buffer);
}
catch(Exception ex)
{
ShowMsg(ex.Message);
}
}
}
}
可以帮我看看,C#TCP服务端运行之后,为什么发信息会显示不在字典中 。
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- CSDN专家-赖老师(软件之家) 2021-06-20 16:27关注
string point = tSocket.RemoteEndPoint.ToString();
打印一下point的值,是否唯一?
解决 无用评论 打赏 举报
悬赏问题
- ¥15 WPF动态创建页面内容
- ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
- ¥15 SQL数据库操作问题
- ¥100 关于lm339比较电路出现的问题
- ¥15 Matlab安装yalmip和cplex功能安装失败
- ¥15 加装宝马安卓中控改变开机画面
- ¥15 STK安装问题问问大家,这种情况应该怎么办
- ¥15 关于罗技鼠标宏lua文件的问题
- ¥15 halcon ocr mlp 识别问题
- ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线