[英]Simple Java Networking Program
I'm new to Java programming and I'm just trying to get a very basic networking program to work. 我是Java编程的新手,我只是想尝试一个非常基本的网络程序。
I have 2 classes, a client and a server. 我有两个类,一个客户端和一个服务器。 The idea is the client simply sends a message to the server, then the server converts the message to capitals and sends it back to the client.
想法是,客户只需将消息发送到服务器,然后服务器将消息转换为大写字母,然后将其发送回客户端。
I'm having no issues getting the server to send a message to the client, the problem is I can't seem to store the message the client is sending in a variable server side in order to convert it and so can't send that specific message back. 我在让服务器向客户端发送消息方面没有问题,问题是我似乎无法将客户端发送的消息存储在变量服务器端以进行转换,因此无法发送该消息具体消息回。
Here's my code so far: 到目前为止,这是我的代码:
SERVER SIDE 服务器端
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket (9091);
while (true) {
System.out.println("Waiting");
//establish connection
Socket client = server.accept();
System.out.println("Connected " + client.getInetAddress());
//create IO streams
DataInputStream inFromClient = new DataInputStream(client.getInputStream());
DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());
System.out.println(inFromClient.readUTF());
String word = inFromClient.readUTF();
outToClient.writeUTF(word.toUpperCase());
client.close();
}
}
}
CLIENT SIDE 客户端
public class Client {
public static void main(String[] args) throws IOException {
Socket server = new Socket("localhost", 9091);
System.out.println("Connected to " + server.getInetAddress());
//create io streams
DataInputStream inFromServer = new DataInputStream(server.getInputStream());
DataOutputStream outToServer = new DataOutputStream(server.getOutputStream());
//send to server
outToServer.writeUTF("Message");
//read from server
String data = inFromServer.readUTF();
System.out.println("Server said \n\n" + data);
server.close();
}
}
I think the problem might be with the 'String word = inFromClient.readUTF();' 我认为问题可能出在“字符串单词= inFromClient.readUTF();” line?
线? Please can someone advise?
有人可以请教吗? Thanks.
谢谢。
You're discarding the first packet received from the client: 您正在丢弃从客户端收到的第一个数据包:
System.out.println(inFromClient.readUTF()); // This String is discarded
String word = inFromClient.readUTF();
Why not swap these? 为什么不交换这些?
String word = inFromClient.readUTF(); // save the first packet received
System.out.println(word); // and also print it
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.