我有任务。通过套接字,传递变量输出。
String hex = "1040014116";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
输出的格式为“ 0x10 ..”
他需要一个Web服务器来传输此数据,并作为回报接收其他服务器。
int serverPort = 2003;
String address = "xx.xx.xx.xx";
try {
InetAddress ipAddress = InetAddress.getByName(address);
System.out.println(" IP address " + address + " and port " + serverPort);
Socket socket = new Socket(ipAddress, serverPort);
System.out.println("Socket ready");
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
System.out.println("Введите данные и нажмите 'Ввод'");
System.out.println();
while (true) {
line = reader.readLine();
System.out.println("Отправка на сервер");
out.writeUTF(line);// отправка текста
System.out.println("Отправка: : " + line);
out.flush(); // конец передачи
line = in.readUTF(); // возврат текста от сервера
System.out.println("Сервер: : " + line);
System.out.println("Введите новую строку");
System.out.println();
}
} catch (Exception x) {
x.printStackTrace();
}
}
作为响应,如何传递位字符串并从服务器获取位字符串。
答案 0 :(得分:0)
您需要在客户端和服务器端都进行编码
服务器代码
ServerSocket sskt=new ServerSocket(port);
Socket =sskt.accept()
InputStream is=skt.getInputStream();
OutputStream os=skt.getOutputStream();
客户代码
Socket skt=new Socket(server_ip,port);
建立连接后,使用相同的输入流和输出流进行读写
希望这会有所帮助