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.
68 lines
2.1 KiB
68 lines
2.1 KiB
package com.vertsys;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.DataOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.InputStreamReader;
|
|
import java.net.Socket;
|
|
import java.util.Random;
|
|
|
|
public class Client {
|
|
|
|
protected static Socket sock;
|
|
private static String username;
|
|
private static BufferedReader ConsoleIn;
|
|
|
|
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 = "localhost";
|
|
int port = 42424;
|
|
|
|
// Falls die Vergabe eines Benutzernamen fehlschlägt --> "test" + Zufallszahl
|
|
Random rand = new Random();
|
|
username = "test" + Integer.toString(rand.nextInt(4));
|
|
try {
|
|
ConsoleIn = new BufferedReader(new InputStreamReader(System.in));
|
|
System.out.print("Your Username: ");
|
|
String user = ConsoleIn.readLine();
|
|
if (user != "")
|
|
username = user;
|
|
System.out.print("Enter Server hostname: ");
|
|
hostname = ConsoleIn.readLine();
|
|
System.out.print("Enter port number: ");
|
|
port = Integer.parseInt(ConsoleIn.readLine());
|
|
}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();
|
|
}
|
|
}
|
|
}
|