Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cd2020create;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.*;
- import java.io.PrintWriter;
- import java.net.*;
- import java.net.Socket;
- import java.util.Date;
- import java.util.Scanner;
- public class SocketClient {
- public static void main(String args[]) throws IOException, NumberFormatException, InterruptedException, NullPointerException {
- String portnos = "0000";
- Scanner sc = new Scanner(System.in);
- InetAddress ip = InetAddress.getByName("10.12.98.56");
- System.out.println("Please enter a port to connect to (max 5 digits).");
- do {
- portnos = sc.next();
- try {
- Integer.parseInt(portnos);
- } catch (Exception e) {
- portnos = "100000000";
- }
- if (Integer.parseInt(portnos) > 99999) {
- System.err.println("Invalid port");
- portnos = "100000000";
- }
- } while (Integer.parseInt(portnos) > 99999);
- Socket sklocal = null;
- Date date = new Date();
- long timeMilli = date.getTime();
- System.out.print("Connecting...");
- long timeMilli2 = date.getTime();
- while (true) {
- if (timeMilli2 - timeMilli > 10000)
- {
- System.err.println("Error: Connection Timeout");
- }
- try {
- sklocal = new Socket(ip, Integer.parseInt(portnos));
- if (sklocal.getRemoteSocketAddress() != null) {
- break;
- }
- } catch (Exception e) {
- timeMilli2 = date.getTime();
- System.out.print(".");
- }
- }
- System.out.println("Connected to " + sklocal.getRemoteSocketAddress());
- System.out.print("Please enter a username (Must not contain spaces): ");
- String username = sc.next();
- System.out.println();
- DataOutputStream dataOut = new DataOutputStream(sklocal.getOutputStream());
- DataInputStream dataIn = new DataInputStream(sklocal.getInputStream());
- boolean useless = false;
- String tempb = "";
- int x = 0;
- while (true) {
- if (x > 0) {
- System.out.print("[" + username + "]" + ": ");
- }
- String input = "[" + username + "]" + ": " + sc.nextLine();
- useless = true;
- dataOut.writeUTF(input);
- if (dataOut.equals(null))
- tempb = dataIn.readUTF();
- System.out.print(tempb);
- if (!(tempb.equals("")))
- {
- System.out.println();
- }
- x++;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement