在c#中使用socket获取数据的正确方法是什么 [英] what is the right way to get the data using socket in c#
本文介绍了在c#中使用socket获取数据的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是Sever Code,我从客户端接收数据但每次在数据前都有一个特殊符号。
例如:
如果客户端发送1然后
在服务器中我将得到外出:@ 1任何符号
像这样得到特殊符号和值。
This is the Sever Code, am receiving the data from the client but every time am getting one special symbol before the data.
For Example :
If client sends 1 then
In The Server i will get outout: @1 any symbols
like this am getting special symbols and values.
try {
int Port = 8088;
TcpListener server = new TcpListener(IPAddress.Any, Port);
server.Start()
byte[] bytes = new byte[1024];
string data;
while (true)
{
Console.Write("Waiting for Client connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("\nClient Connected....!");
NetworkStream stream = client.GetStream();
int i;
i = stream.Read(bytes, 0, bytes.Length);
while (i != 0)
{
i = stream.Read(bytes, 0, bytes.Length);
data = System.Text.Encoding.ASCII.GetString(bytes, 0,i);
Console.WriteLine(string.Format("Received:{0}",data));
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
推荐答案
您不能直接应用AcceptTcpClient,就好像它返回客户端实例一样。它也是完全无用的,因为你只能从也作为服务器运行的软件连接。
这里有几个关于codeproject的例子,你可以查看:
用C#编写的TCP / IP服务器 [ ^ ]
更高级:
C#.NET中的完整TCP服务器/客户端通信和RMI框架 - 实现 [ ^ ]
简单示例:
http://tech.pro/tutorial/704/csharp -t utorial-simple-threaded-tcp-server [ ^ ]
祝你好运!
You can't directly apply AcceptTcpClient as if it returns a client instance. It would also be complete useless because you could only connect from the software that also runs as a server.
There are several examples here on codeproject you can check out:
A TCP/IP Server written in C#[^]
More advanced:
A Complete TCP Server/Client Communication and RMI Framework in C# .NET - Implementation[^]
Simple example:
http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server[^]
Good luck!
int Port = 8088;
TcpListener server = new TcpListener(IPAddress.Any, Port);
server.Start();
byte[] bytes = new byte[1024];
string data;
Console.Write("Waiting for Client connection ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("\n Client Connected");
NetworkStream stream = client.GetStream();
int i;
i = stream.Read(bytes, 0, bytes.Length);
data = Encoding.UTF8.GetString(bytes, 0, i);
data=data.Substring(2, data.Length-2);
Console.WriteLine(string.Format("Data Received :{0}", data));
client.Close()
这篇关于在c#中使用socket获取数据的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文