1.socket 通信传输汉字的方法:Encoding.GetEncoding("GB2312").GetString(Receivebyte) 发送接收都这样转化
直接上程序
public partial class Form1 : Form { public Form1() { InitializeComponent(); } //定义委托 public delegate void ShowMessageHandel(string msg); //向控件添加显示信息 public void showMsg(string msg) { listBox1.Items.Add(msg); } private void Form1_Load(object sender, EventArgs e) { //Control.CheckForIllegalCrossThreadCalls = false; Thread th = new Thread(new ThreadStart(ServerSocket)); th.Start(); // ServerSocket(); } Socket client; public void ServerSocket() { IPEndPoint ipP = new IPEndPoint(IPAddress.Parse("192.168.1.104"), 6000); Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketServer.Bind(ipP); while (true) { socketServer.Listen(5); client = socketServer.Accept(); Thread thClient = new Thread(new ThreadStart(ClientSocket)); thClient.Start(); } } public void ClientSocket() { ShowMessageHandel smh = showMsg; byte[] byteMsg = new byte[1024]; while (true) { client.Receive(byteMsg, byteMsg.Length, SocketFlags.None); client.Send(System.Text.ASCIIEncoding.UTF8.GetBytes("你好")); client.Send(UTF8Encoding.GetEncoding("GB2312").GetBytes("你好")); // listBox1.Items.Add(Encoding .ASCII.GetString(byteMsg)); //可收发汉字 string strMsg = UTF8Encoding.GetEncoding("GB2312").GetString(byteMsg); this.BeginInvoke(smh, strMsg);//委托简单调用 } } }
上面代码仅供参考,有肯多不足,请多指教
时间: 2024-09-17 06:12:53