tcp 通讯问题
服务端接受客户端发送的数据receiveData ,经过一系列处理返回字符串responseMsg,如何将responseMsg字符串发送给客户端,outputStream.write是以字符数组方式发送的,能不能以字符串形式发送?
public void start(int port) {
ServerSocket serveSocket = null;
Socket clientSocket = null;
BufferedInputStream input = null;
byte[] buffer = new byte[1024];
ByteArrayOutputStream bops = new ByteArrayOutputStream(); // 请求数据存放对象
try {
serveSocket = new ServerSocket(port); // 在指定端口建立一个连接
System.out.println("服务器开始监听:");
while (true) {
clientSocket = serveSocket.accept(); // 收到一个信息,得到一个clientSocket
InputStream inputStream = clientSocket.getInputStream(); // 数据缓冲区
OutputStream outputStream = clientSocket.getOutputStream();
int count = 0; // 每个缓冲区的实际数据长度
try {
input = new BufferedInputStream(inputStream);
count = input.read(buffer);
bops.write(buffer, 0, count);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (Exception f) {
f.printStackTrace();
}
}
}
String receiveData = bops.toString();
System.out.println("收到如下报文: " + receiveData);
String responseMsg = do(receiveData);
responseMsg = "1234567890";
try{
outputStream.write(responseMsg.getBytes());
}
catch(Exception e)
{
e.printStackTrace();
}
outputStream.close();
bops.reset();
inputStream.close();
clientSocket.close();
} else {
outputStream.close();
GeneralLog.error(COMM_MODULE, "接收的数据为null或空串!");
bops.reset();
inputStream.close();
clientSocket.close();
}
}
} catch (Exception e) {
e.printStackTrace();
log.error(e);
}
}
------解决方案--------------------
输入流和输出流肯定都是字节流啊,将字符串转化为字节数组通过String.getBytes()或者
String.getBytes(encoding)就可以啊,也不麻烦啊,如果上层调用的是字符串,你将socket通讯封装成一个方法就可以啊