栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用套接字发送和接收数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用套接字发送和接收数据

我假设您正在使用TCP套接字进行客户端-
服务器交互?将不同类型的数据发送到服务器并能够区分两者的一种方法是将第一个字节(如果消息类型超过256种,则使用更多字节)作为某种标识符。如果第一个字节为1,则为消息A,如果为2,则为消息B。通过套接字发送此消息的一种简单方法是使用

DataOutputStream/DataInputStream

客户:

Socket socket = ...; // Create and connect the socketDataOutputStream dOut = new DataOutputStream(socket.getOutputStream());// Send first messagedOut.writeByte(1);dOut.writeUTF("This is the first type of message.");dOut.flush(); // Send off the data// Send the second messagedOut.writeByte(2);dOut.writeUTF("This is the second type of message.");dOut.flush(); // Send off the data// Send the third messagedOut.writeByte(3);dOut.writeUTF("This is the third type of message (Part 1).");dOut.writeUTF("This is the third type of message (Part 2).");dOut.flush(); // Send off the data// Send the exit messagedOut.writeByte(-1);dOut.flush();dOut.close();

服务器:

Socket socket = ... // Set up receive socketDataInputStream dIn = new DataInputStream(socket.getInputStream());boolean done = false;while(!done) {  byte messageType = dIn.readByte();  switch(messageType)  {  case 1: // Type A    System.out.println("Message A: " + dIn.readUTF());    break;  case 2: // Type B    System.out.println("Message B: " + dIn.readUTF());    break;  case 3: // Type C    System.out.println("Message C [1]: " + dIn.readUTF());    System.out.println("Message C [2]: " + dIn.readUTF());    break;  default:    done = true;  }}dIn.close();

显然,您可以发送各种数据,而不仅仅是字节和字符串(UTF)。

请注意,它将

writeUTF
写一种修改的UTF-8格式,其后是一个无符号的两字节编码整数的长度指示符,该整数指示您
2^16 - 1 =65535
要发送的字节。这样就可以
readUTF
找到编码字符串的结尾。如果决定自己的记录结构,则应确保记录的结尾和类型是已知的或可检测的。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496528.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号