Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.Objects;
- public class Client {
- public static void main(String[] args) {
- Client c1 = new Client(9001);
- //Client c2 = new Client(9002);
- //c1.createConnection("192.168.0.24", 9002);
- //c1.send.send("connect");
- }
- ClientSend send;
- ClientReceive receive;
- int port;
- public Client(int myPort) {
- port = myPort;
- receive = new ClientReceive(myPort);
- }
- public void createConnection(String otherIp, int otherPort) {
- send = new ClientSend(otherIp, otherPort);
- }
- private class ClientSend {
- private Socket socket;
- private BufferedReader fromServer;
- private PrintWriter toServer;
- public ClientSend(String otherIp, int otherPort) {
- try
- {
- socket = new Socket(otherIp, otherPort);
- toServer = new PrintWriter(socket.getOutputStream(), true);
- fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- }
- catch (IOException e)
- {
- socket = null;
- toServer = null;
- fromServer = null;
- }
- }
- private void send(String msg) {
- System.out.println("Sending ( "+ port + "): " + msg);
- toServer.println(msg);
- }
- }
- private class ClientReceive {
- private ServerSocket serverSocket;
- public ClientReceive(int port) {
- try {
- serverSocket = new ServerSocket(port);
- } catch (IOException e) {
- serverSocket = null;
- }
- new Handler(serverSocket).start();
- }
- private void receive(String msg) {
- System.out.println("Received: (" + port + ")" + msg);
- if(msg.equals("connect")) {
- send = new ClientSend("localhost", 9001);
- send.send("lol");
- }
- }
- private class Handler extends Thread {
- private final ServerSocket socket;
- public Handler(ServerSocket pSocket) {
- socket = pSocket;
- }
- public void run()
- {
- while (true)
- {
- Socket clientSocket = null;
- BufferedReader fromClient = null;
- try
- {
- clientSocket = serverSocket.accept();
- }
- catch (IOException e)
- {
- /*
- * Kann keine Verbindung zum anfragenden Client aufgebaut werden,
- * geschieht nichts.
- */
- }
- if(clientSocket!= null) {
- try {
- fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- } catch (IOException ignored) {
- }
- while (socket != null) {
- String msg = null;
- try {
- msg = fromClient.readLine();
- } catch (IOException ignored) {
- }
- if(!Objects.equals(msg, "")) {
- ClientReceive.this.receive(msg);
- }
- }
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement