c#的socket编程中,怎么获取接受到得数据长度

RT,好的有加分!!!
2024-11-08 21:43:40
推荐回答(5个)
回答(1):

//测试URL程序 客户端和服务器端在后面
public class TestURL {
public static void main(String[] args) throws IOException {
//构建一URL对象
URL url=new URL("file:///C:/test.out");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
//使用openStream得到一输入流并由此构造一个BufferedReader对象
String inputLine;
while ((inputLine = in.readLine()) != null)
//从输入流不断的读数据,直到读完为止
System.out.println(inputLine); //把读入的数据打印到屏幕上
in.close(); //关闭输入流
}
}

客户端程序
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException, IOException {
//向本机的4700端口发出请求
Socket socket=new Socket("localhost",4700);
//由系统标准输入创建一个输入流,负责接收界面输入的数据
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//由Socket对象得到一个输出流
//负责向服务器端发送数据
PrintWriter pw=new PrintWriter(socket.getOutputStream());
//由Socket得到一个对象的输入流
//负责接收服务器端返回的信息
BufferedReader brsocket=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readLine;
//从标准输入设备上接收传入的一个字符串
System.out.println("请您输入向服务器的数据");
readLine=br.readLine();
//如果页面传入bye,则结束循环
while(!readLine.equals("bye")){
/*向服务器发送接收到的字符串*/
pw.println(readLine);
pw.flush();
//在标准输出设备上输出刚才发送给服务器的数据
System.out.println("Client:"+readLine);
//输出从服务器端得到的数据
System.out.println("正在等待接收服务器端信息:");
System.out.println("Server:"+brsocket.readLine());
//从标准输入设备上接收传入的一个字符串
System.out.println("请您输入向服务器的数据");
readLine=br.readLine();
}
brsocket.close();
pw.close();
br.close();
socket.close();
}
}
服务端程序
public class ServerDemo {
public static void main(String[] args) throws IOException {
/*创建服务器监听的接口*/
ServerSocket server=new ServerSocket(4700);
//使用accept()阻塞等待客户请求,有客户
//请求到来则产生一个Socket对象,并继续执行
Socket socket=server.accept();
String line;
//由Socket对象得到一个输入流,负责从客户端接收数据
BufferedReader brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到一个输出流,负责向客户端发送数据
PrintWriter pw=new PrintWriter(socket.getOutputStream());
//创建一个标准输入设备的输入流
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
//在标准输出设备上输出从客户端得到的数据
System.out.println("正在等待客户端的数据......");
System.out.println("Client:"+brin.readLine());
System.out.println("请您输入要向客户端发送的信息:");
//从标准输入设备上得到字符串
line=in.readLine();
////如果该字符串为 "bye",则停止循环
while(!line.equals("bye")){
//向客户端输出信息
pw.println(line);
pw.flush();
//在标准输出设备上输出刚才Server读入的字符串
System.out.println("Server:"+line);
//输出刚才从客户端读入的数据
System.out.println("正在等待客户端的数据......");
System.out.println("Client"+brin.readLine());
System.out.println("请您输入要向客户端发送的信息:");
line=in.readLine();
}
brin.close();
in.close();
pw.close();
server.close();
socket.close();
}
}

回答(2):

......直接读成二进制流,在接收端或者说服务器端接收到二进制流后 以同样的类型进行转换就好

看下这个方法.将数组类型读取为二进制流
private byte[] SerializeOnlineList()
{
StringCollection onlineList = new StringCollection();
foreach (object o in _transmit_tb.Keys)
{
onlineList.Add(o as string);
}
IFormatter format = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
format.Serialize(stream, onlineList);
byte[] ret = stream.ToArray();
stream.Close();
return ret;
}

而这是接收端的行为
byte[] onlineBuff = new byte[_maxPacket];
int byteCnt = _nws.Read(onlineBuff, 0, onlineBuff.Length);
IFormatter format = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
stream.Write(onlineBuff, 0, byteCnt);
stream.Position = 0;
StringCollection onlineList = (StringCollection)format.Deserialize(stream);

其它类型都可以这样进行转换.StringCollection只是一个类型,你可以利用任何类型进行同样的操作 ...至于怎么发送数据这个不用我说了吧.NetworkStream 本身有Write和Read方法貌似

1.简单服务器端
//using System.Data;
//using System.net.Sockets;
//using System.net;
//using System.Threading;
int port=%%2;
private Thread thThreadRead;
private TcpListener TcpListen;
private bool bListener=true;
private Socket stRead;
void Listen()
{
tlTcpListen=new TcpListener(port);
tlTcpListen.Start();
stRead=tlTcpListen.AccepSocket();
EndPoint tempRemoteEP=skSocket.RemoteEndPoint;
IPEndPoint tempRemoteIP=(IPEndPoint)tempRemoteEP;
IPHostEntry host=Dns.GetHostByAddress(tempRemoteIP.Address);
string sHostName=host.HostName;
while(bListener)
{
string sTime=DateTime.Now.ToShortTimeString();
Byte[] byRead=new Byte[1024];
int iRead=stRead.ReceiveFrom(byRead,ref tempRemoteEP);
Byte[] byText=new Byte[iRead];
Array.Copy(byRead,0,byText,0,iRead);
string %%5=System.Text.Encoding.Default.GetString(stream);
}
}
catch(Security.SecurityException)
{
//监听失败
}
}
thThreadRead=new Thread(new ThreadStart(Listen));
thThreadRead.Start();

2.简单客户端
//using System.Data;
//using System.net.Sockets;
//using System.net;
int port=%%1;
private TcpClient tcpc;
private Socket stSend;
private bool tcpConnect=false;
try{
stSend=new Socket(AddressFamily.InterNetwok,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint tempRemoteIP=(IPEndPoint)tempRemoteEP;
EndPoint epTemp=(EndPoint)tempRemoteIP;
stSend.Connect(epTemp);
tcpConnect=true;
}
catch(Exception)
{
//目标计算机拒绝了连接请求!
}
int iLength=%%3.Length;
Byte[] bySend=new byte[iLength];
bySend=System.Text.Encoding.Default.GeBytes(%%3);
int retVal=stSend.Send(bySend);
}
protected override void Dispose(bool disposing)
{
if(tcpConnect)
{
stSend.Close();
}
if(disposing && component!=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}

3.获得本机IP
//using System.Net;
IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
string s=null;
for (int i = 0; i < addressList.Length; i++)
{
s += addressList[i].ToString();
}
%%1=s;

回答(3):

TcpClient clientSocket = null;
NetworkStream ns = null;
StreamReader sr = null;
StreamWriter sw = null;
bool connected = false;
private void ConnectToServer(object myobject)
{
try
{
if (clientSocket == null || !clientSocket.Connected)
{
clientSocket = new TcpClient("127.0.0.1", 7710);
ns = clientSocket.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
connected = true;

if (connected)
{
receive = new Thread(new ThreadStart(ReceiveChat));
receive.Start();
}
}
else
{
sw.WriteLine(textBox1.Text);
sw.Flush();
}
}
catch {
connected = false;
}
}
}
private void ReceiveChat()
{
try
{
while (true)
{
byte[] buffer = new byte[1024];
timer1.Enabled = true;
timer1.Start();
ns.Read(buffer, 0, buffer.Length);
timer1.Enabled = false;

string receiveStr=System.Text.Encoding.ASCII.GetString(buffer).TrimEnd('\0');
int receiveLength=receiveStr.Length;//接受数据长度

}
}
catch {
connected = false;
}
}

回答(4):

建议参照http协议自己设置头信息,不然不可能未卜先知的得到整个流中数据的长度

回答(5):

这里是java专栏哦。建议你去论坛去问下。这里仅仅类似于百货商场哦 祝你好运