我正在研究一个java套接字程序,并且与客户端部分有差异。服务器获取所有客户端写的内容,但客户端只获取它写的内容。有人可以向我提供一个程序的客户端部分示例,它可以获取所有客户编写的内容吗?谢谢!
答案 0 :(得分:1)
这是一个“回声服务器”示例
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws IOException
{
ServerSocket serverSocket = null;
DataInputStream serverInput = null;
PrintStream serverOutput = null;
String line = null;
Socket clientSocket = null;
// create server socket
try
{
serverSocket = new ServerSocket(2012);
clientSocket = serverSocket.accept();
serverInput = new DataInputStream(clientSocket.getInputStream());
serverOutput = new PrintStream(clientSocket.getOutputStream());
}
catch(IOException e){System.out.println(e);}
// receive data and send it back to the client
try
{
while(true)
{
line = serverInput.readLine();
if(line.equals("exit"))
{
break;
}
else
{
if(!line.equals(null) && !line.equals("exit"))
{
System.out.println("Received " +line);
line = line+" MODIFIED";
serverOutput.println(line);
}
}
}
}
catch(IOException e){System.out.println("SERVER SIDE: Unable send/receive data");}
try
{
serverInput.close();
serverOutput.close();
clientSocket.close();
serverSocket.close();
}
catch(IOException e){System.out.println(e);}
}
}
这是客户端
import java.io.*;
import java.net.*;
public class TCPClient
{
public static void main(String[] args) throws IOException
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 2012);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
if(userInput.equals("exit"))
break;
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}