мне интересно, есть ли две программы, одна из которых называется server
, а другая - client
, и эти две иллюстрируют сервер и клиент соответственно, возможно ли проверить их на одной машине?учитывая, что я определил сокет клиента следующим образом:
socket = new Socket("127.0.0.1",3000);
Редактировать: Серверная часть:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
class TCPServer
{
private static ServerSocket serverSocket;
private static Socket socket;
private static PrintWriter toClient;
private static BufferedReader fromClient;
public static void run() throws IOException
{
System.out.println("Server is waiting for connections...");
while (true)
{
openStreams();
processClient();
closeStreams();
}
}
public static void openStreams() throws IOException
{
serverSocket = new ServerSocket(3000);
socket = serverSocket.accept();
toClient = new PrintWriter(socket.getOutputStream(),true);
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
public static void closeStreams() throws IOException
{
fromClient.close();
toClient.close();
socket.close();
serverSocket.close();
}
public static void processClient()throws IOException
{
String msg = null;
do {
msg = fromClient.readLine();
toClient.println("Client said " + msg);
} while (!"exit".equals(msg));
}
}
Клиентская часть:
package clientserver.pkg1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
class TCPClient
{
private PrintWriter toServer;
private BufferedReader fromServer;
private Socket socket;
public void Client( )throws IOException
{
socket = new Socket("127.0.0.1",3000);
}
public void openStreams() throws IOException
{
toServer = new PrintWriter(socket.getOutputStream(),true);
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
public void closeStreams() throws IOException
{
fromServer.close();
toServer.close();
socket.close();
}
public void run()throws IOException
{
openStreams();
String msg = "";
Scanner scanner = new Scanner(System.in);
while (!"exit".equals(msg))
{
System.out.print(">");
msg = scanner.nextLine();
toServer.println(msg);
String tmp = fromServer.readLine();
System.out.println("Server said: " + tmp);
}
closeStreams();
}
}
Основной класс
public static void main(String[] args) {
try
{
TCPServer server = new TCPServer() {};
TCPClient client = new TCPClient();
client.run();
server.run();
}
catch(IOException e)
{
System.err.println("Error in Client " + e.getMessage());
}
java.lang.NullPointerException
1
toServer = new PrintWriter(socket.getOutputStream(),true);
2
public void run()throws IOException
{
openStreams();
.....
}
3
public static void main(String[] args) {
try
{
TCPClient client = new TCPClient();
client.run();
}
при client.run();