JAVA TCP 客户端-服务器连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39903732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA TCP Client-Server connection
提问by n00bie1221
When I run this program the Client class prompts the user to enter a command, and that command should go to the Server class and open a file and read each line of that file and return the byte length back to the Client class to be displayed.
当我运行这个程序时,Client 类会提示用户输入一个命令,该命令应该转到 Server 类并打开一个文件并读取该文件的每一行并将字节长度返回给 Client 类以进行显示。
Unfortunately once i enter the command, nothing happens & Not sure why.
不幸的是,一旦我输入命令,就什么也没有发生并且不知道为什么。
TCP Client Class
TCP客户端类
package TcpClient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.io.*;
public class TcpClient {
public static void main(String[] args) {
String temp;
String displayBytes;
try {
//create input stream
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
//create client socket, connect to server
Socket clientSocket = new Socket("localhost",5555);
//create output stream attached to socket
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
System.out.print("Command : ");
//create input stream attached to socket
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
temp = inFromUser.readLine();
//send line to server
outToServer.writeBytes(temp);
//read line from server
//displayBytes = inFromServer.readLine();
while((displayBytes = inFromServer.readLine()) != null) {
System.out.print(displayBytes);
}
//clientSocket.close();
}
catch(Exception ex) {
}
}
}
TCP Server Class
TCP 服务器类
package TcpServer;
import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
// The name of the file to open.
String fileName = "input.txt";
// This will reference one line at a time
String line = null;
String holder=null;
String clientWord;
int bytNumber;
try {
//create welcoming socket at port 5555
ServerSocket welcomeSocket = new ServerSocket(5555);
//wait, on welcoming socket for contact by client
Socket connectionSocket = welcomeSocket.accept();
//create input stream, attached to socket
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
//create output stream, attached to socket
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
//read in line from socket
clientWord = inFromClient.readLine();
if(clientWord.equals("query")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader buffer = new BufferedReader(fileReader);
while((line = buffer.readLine()) != null) {
System.out.println(line);
bytNumber = line.getBytes().length;
holder=Integer.toString(bytNumber);
//pr.println(bytNumber);//only printing first line not going until eof
outToClient.writeBytes(holder);
// line = buffer.readLine();
// pr.flush();
}
// Always close files.
buffer.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println ("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}// end if statement
}
catch(Exception ex) {
}
}
}
回答by gjigandi
I suggest you to only DataOutputStream
and DataInputStream
in both sides and to not use BufferedInputStream
.
The slightly modified code below is able to correctly send the message from the client to the server. Now you can easily make it work for what you want to achieve.
我建议你只DataOutputStream
和DataInputStream
两侧并没有使用BufferedInputStream
。下面稍微修改的代码能够正确地将消息从客户端发送到服务器。现在,您可以轻松地让它为您想要实现的目标服务。
Server
服务器
import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
// The name of the file to open.
String fileName = "input.txt";
// This will reference one line at a time
String line = null;
String holder=null;
String clientWord;
int bytNumber;
try
{
//create welcoming socket at port 5555
ServerSocket welcomeSocket = new ServerSocket(5555);
//wait, on welcoming socket for contact by client
Socket connectionSocket = welcomeSocket.accept();
//create input stream, attached to socket
DataInputStream inFromClient =
new DataInputStream(connectionSocket.getInputStream());
//create output stream, attached to socket
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
//read in line from socket
clientWord = inFromClient.readUTF();
System.out.println(clientWord);
if(clientWord.equals("query"))
{
try
{
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader buffer = new BufferedReader(fileReader);
while((line = buffer.readLine()) != null)
{
System.out.println(line);
bytNumber = line.getBytes().length;
holder=Integer.toString(bytNumber);
//pr.println(bytNumber);//only printing first line not going until eof
outToClient.writeBytes(holder);
// line = buffer.readLine();
// pr.flush();
}
// Always close files.
buffer.close();
}
catch(FileNotFoundException ex)
{
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex)
{
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}// end if statement
}
catch(Exception ex)
{
}
}
}
Client
客户
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.io.*;
public class TcpClient {
public static void main(String[] args) {
String temp;
String displayBytes;
try
{
//create input stream
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
//create client socket, connect to server
Socket clientSocket = new Socket("localhost",5555);
//create output stream attached to socket
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
System.out.print("Command : ");
//create input stream attached to socket
DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());
temp = inFromUser.readLine();
//send line to server
//outToServer.writeBytes(temp);
outToServer.writeUTF(temp);
outToServer.flush();
//read line from server
//displayBytes = inFromServer.readLine();
while((displayBytes = inFromServer.readUTF()) != null)
{
System.out.print(displayBytes);
}
//clientSocket.close();
}
catch(Exception ex)
{
}
}
}