我试图在客户端-服务器体系结构中使用Socket发送一个简单的字节数组。使用Netbeans进行调试也存在一些问题,因为它提供了:
SocketException:连接重置
因此,我在代码下方发布内容,非常希望有人帮助我。
客户:
public class TestClient {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1", 3242);
byte[] b;
b = "Hello".getBytes();
DataOutputStream os = new DataOutputStream(s.getOutputStream());
os.write(b);
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务器:
public class TestServer {
public static void main(String[] args) {
try {
byte[] b = new byte[5];
Socket s = new ServerSocket(3242).accept();
DataInputStream is = new DataInputStream(s.getInputStream());
is.read(b);
System.out.println(String.valueOf(b));
} catch (Exception e) {
e.printStackTrace();
}
}
}
我试图简单地使用InputStream和OutputStream,但是行为是相同的。
运行上述代码的结果是:
[B@25154f
感谢您的关注。
最佳答案
尝试取代这个
System.out.println(String.valueOf(b));
有了这个:
System.out.println(new String(b));
这将使用
String
将字节数组转换为default encoding
。如果服务器和客户端使用相同的default encoding
,它将起作用,否则,您需要在下一步中在双方中指定编码:在
TestClient
"Hello".getBytes(encoding)
在
TestServer
System.out.println(new String(b, encoding))