Socket temp = s.Accept();//为新建连接创建新的socket
Console.WriteLine("建立连接");
string recvStr = "";
byte[] recvBytes = new byte[2048];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("时间"+DateTime.Now+" 服务器获取数据:{0}", recvStr);//把客户端传来的信息显示出来客户端发送的16进制数据 就会变成乱码
不是16进制就好好的 ,本人新手 希望大侠们 帮忙解决下
参考
http://blog.163.com/epeda@126/blog/static/4180347820118604343550/
服务端代码private void button1_Click(object sender, EventArgs e)
{
IPAddress localip = IPAddress.Parse("10.11.1.2");
IPEndPoint ipep = new IPEndPoint(localip,6000);//
Socket server1 = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
server1.Bind(ipep);//参数为主机对象 IPEndPoint
server1.Listen(50);//参数整型数值,挂起队列最大值
Socket clientsocket = server1.Accept();//接收客户端的连接请求
byte[] sendd1 = new byte[1024];
string senddata1 = "hi";
sendd1 = ASCIIEncoding.ASCII.GetBytes(senddata1);
byte[] sendd2 = new byte[1024];
string senddata2 = "no problem";
sendd2 = ASCIIEncoding.ASCII.GetBytes(senddata2); byte[] received = new byte[1024];
clientsocket.Receive(received,received.Length,0);
string receivedata = Encoding.BigEndianUnicode.GetString(received);//.BigEndianUnicode.GetString(received);
richTextBox1.AppendText(receivedata+"收到的消息"+"\r\n");
}
{
IPAddress ipin = IPAddress.Parse("10.11.1.2");
IPEndPoint ipep = new IPEndPoint(ipin,6000);
Socket clienta = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
clienta.Connect(ipep); string senddata1 =textBox1.Text ;
byte[] senddata2 = new byte[1024];
senddata2 = ASCIIEncoding.ASCII.GetBytes(senddata1);
clienta.Send(senddata2);
richTextBox1.AppendText(senddata1+"发送成功!"+"\r\n");
}
谁来帮我解决下问题呀 ..愁死了 .
乱码问题是因为你客户端的编码是用:ASCIIEncoding.ASCII.GetBytes(senddata1);
而服务器解码的编码格式是:Encoding.BigEndianUnicode.GetString(received);
所以,乱码是必然的,这两个要一致/
谁来帮我解决下问题呀 ..愁死了 .
[/Quote]那个图是模拟程序吧,对方难道没有给你电文的协议?就是电文格式?
服务端string receivedata = ASCIIEncoding.ASCII.GetString(received);结果显示正常了。谢谢啦。
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < count; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
用上面的方法把字节转下 就好了 能正常显示了
tcp终于搞定了 下面又得搞udp了 真蛋疼.
感谢OROCHIHeart,dhxyxiaofeng感谢大家