Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

homework 6 #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
homework 6
  • Loading branch information
alerausm committed Sep 10, 2018
commit 8caf7166aca43eb5aff382af860dcf4829f107b8
5 changes: 5 additions & 0 deletions lesson6/src/GeekChat.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
public interface GeekChat extends Runnable {
int SERVER_PORT_DEFAULT = 3345;
String SERVER_HOST_DEFAULT = "localhost";
void postMessage(String string);
}
41 changes: 41 additions & 0 deletions lesson6/src/GeekChatClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class GeekChatClient implements Runnable, GeekChat {
DataOutputStream outputStream;
@Override
public void run() {
try(Socket socket = new Socket(GeekChat.SERVER_HOST_DEFAULT,GeekChat.SERVER_PORT_DEFAULT)) {
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("Ready for chat... ");
while (true){
String response = inputStream.readUTF();
if (response!=null && !response.isEmpty())
System.out.println("Server: "+response);
try {
Thread.sleep(333);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
catch (UnknownHostException e) {
System.out.println("No such host");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

@Override
public void postMessage(String string) {
try {
outputStream.writeUTF(string);
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}

}
}
80 changes: 80 additions & 0 deletions lesson6/src/GeekChatServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class GeekChatServer implements GeekChat {
DataOutputStream outputStream = null;
GeekChatServer(){

}
@Override
public void run() {
while (true) {
DataInputStream inputStream = null;
Socket client = null;
try (ServerSocket server = new ServerSocket(GeekChat.SERVER_PORT_DEFAULT)) {
System.out.print("Waiting for client...");
client = server.accept();
System.out.print("Client conntected...");
outputStream = new DataOutputStream(client.getOutputStream());
System.out.println("Ready to send message...");
inputStream = new DataInputStream(client.getInputStream());
System.out.println("Ready to receive message...");
while (client.isConnected()) {
String message = inputStream.readUTF();
System.out.println("Client: " + message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {

System.out.println("Client disconnected");
System.out.println("Closing connections & channels.");

if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Closing connections & channels - DONE.");
}
}

}


@Override
public void postMessage(String message) {
if (outputStream==null) {
System.out.println("Client not conntected yet");
return;
}
try {
outputStream.writeUTF(message);
outputStream.flush();
} catch (IOException e) {
System.out.println("Can't send message to client: " + e.getMessage());
e.printStackTrace();
}

}
}
45 changes: 45 additions & 0 deletions lesson6/src/Homework6.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import java.util.Scanner;
/**
* Java 2 course by GeekBrains. Homework 6.
* @author A.Usmanov
* @version dated 2018-09-10
* Написать консольный вариант клиент\серверного приложения, в котором пользователь может писать сообщения как на клиентской стороне, так и на серверной. Т.е. если на клиентской стороне написать «Привет», нажать Enter, то сообщение должно передаться на сервер и там отпечататься в консоли. Если сделать то же самое на серверной стороне, сообщение, соответственно, передаётся клиенту и печатается у него в консоли. Есть одна особенность, которую нужно учитывать: клиент или сервер может написать несколько сообщений подряд. Такую ситуацию необходимо корректно обработать.
* Разобраться с кодом с занятия — он является фундаментом проекта-чата.
* ВАЖНО! Сервер общается только с одним клиентом, т.е. не нужно запускать цикл, который будет ожидать второго/третьего/n-го клиента.
*/
public class Homework6 {
private static final String MODE_SERVER = "server";
private static final String MODE_CLIENT = "client";

public static void main(String... args) {
String mode = "";
GeekChat chat = null;
for (String arg:args) {
if (arg.equalsIgnoreCase(MODE_SERVER)) {
mode = MODE_SERVER;
break;
}
else if (arg.equalsIgnoreCase(MODE_CLIENT)) {
mode = MODE_CLIENT;
break;
}
}
if (mode==MODE_SERVER) {

chat = new GeekChatServer();
}
else if (mode==MODE_CLIENT) {
chat = new GeekChatClient();
}
else {
System.out.println("please use SERVER or CLIENT key");
return;
}
Thread threadChat = new Thread(chat);
threadChat.start();
Scanner scanner = new Scanner(System.in);
while(threadChat.isAlive()) {
chat.postMessage(scanner.nextLine());
}
}
}