forked from tgeier/online-chat-ueb3
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
2.7 KiB
84 lines
2.7 KiB
package com.vertsys;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.DataOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.InputStreamReader;
|
|
import java.net.InetAddress;
|
|
import java.net.Socket;
|
|
import java.net.UnknownHostException;
|
|
import java.util.Random;
|
|
|
|
import static com.vertsys.Server.DEBUG_MODE;
|
|
|
|
public class Client {
|
|
|
|
protected static Socket sock;
|
|
private static String username;
|
|
private static BufferedReader ConsoleIn;
|
|
private static final boolean DEBUG_MODE = true;
|
|
|
|
public static void main(String[] args) {
|
|
init();
|
|
do {
|
|
try {
|
|
String msg = ConsoleIn.readLine();
|
|
sendMessage(msg);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}while (true);
|
|
}
|
|
|
|
public static void init(){
|
|
String hostname = null;
|
|
try {
|
|
hostname = InetAddress.getLocalHost().getHostAddress();
|
|
if(DEBUG_MODE)
|
|
System.out.println("Host-IP: " + hostname);
|
|
} catch (UnknownHostException e) {
|
|
e.printStackTrace();
|
|
}
|
|
int port = 42424;
|
|
|
|
// Falls die Vergabe eines Benutzernamen fehlschlägt --> "test" + Zufallszahl
|
|
Random rand = new Random();
|
|
username = "test" + Integer.toString(rand.nextInt());
|
|
try {
|
|
ConsoleIn = new BufferedReader(new InputStreamReader(System.in));
|
|
System.out.print("Your Username: ");
|
|
String user = ConsoleIn.readLine();
|
|
if (!user.isEmpty())
|
|
username = user;
|
|
System.out.print("Enter Server hostname: ");
|
|
String host = ConsoleIn.readLine();
|
|
if(!host.isEmpty())
|
|
hostname = host;
|
|
System.out.print("Enter port number: ");
|
|
String portNum = ConsoleIn.readLine();
|
|
if(!portNum.isEmpty())
|
|
port = Integer.parseInt(portNum);
|
|
}catch (IOException e){
|
|
e.printStackTrace();
|
|
}
|
|
try {
|
|
sock = new Socket(hostname, port);
|
|
System.out.println("Connection established!");
|
|
System.out.println("--------------------------------");
|
|
System.out.println("");
|
|
new Thread(new ClientThread()).start();
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
public static void sendMessage(String message){
|
|
String moddedMessage = username + " wrote: " + message + "\n";
|
|
try {
|
|
DataOutputStream toServer = new DataOutputStream(sock.getOutputStream());
|
|
toServer.writeBytes(moddedMessage);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|