Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package chatapplication;
- public class ChatApplication {
- public static void main (String args[]){
- ChatController c = null;
- try {
- c = new ChatController(3666);
- System.out.println("connected");
- c.startReading();
- c.startWriting();
- c.close();
- } catch (java.io.IOException e){
- System.out.format("Couldn't not estabilish a connection (%s)", e.getMessage());
- }
- }
- }
- <<<<<<<<<< ChatController class >>>>>>>>>>>>>>>>>>
- package chatapplication;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.Scanner;
- public class ChatController extends Thread {
- private ServerSocket server = null;
- private Host host = null;
- private Scanner reader = null;
- public ChatController(int port) throws IOException{
- this.server = new ServerSocket(port);
- this.reader = new Scanner(System.in);
- this.host = new Host(server.accept());
- }
- public ChatController(String address, int port) throws IOException{
- this.host = new Host(new Socket(address, port));
- this.reader = new Scanner(System.in);
- }
- @Override
- public void run (){
- while (this.isConnected()){
- System.out.println(this.host.read());
- }
- }
- public void startReading () {
- this.start();
- }
- public void startWriting (){
- while (this.isConnected()){
- this.host.write(this.reader.nextLine());
- }
- }
- public boolean isConnected(){
- return this.host.isConnected();
- }
- public void close () throws IOException{
- this.host.close();
- if (server != null){
- server.close();
- }
- }
- }
- <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Host class >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- package chatapplication;
- import java.util.Scanner;
- import java.io.PrintStream;
- import java.net.Socket;
- public class Host {
- private Socket socket;
- private Scanner reader;
- private PrintStream writer;
- public Host (Socket socket) throws java.io.IOException{
- this.socket = socket;
- this.reader = new Scanner(socket.getInputStream());
- this.writer = new PrintStream(socket.getOutputStream());
- }
- /**
- * Writes content to the connected socket.
- * @param text, the content to send to the other socket.
- */
- public void write(String text){
- this.writer.println(text);
- this.writer.flush();
- }
- /**
- * Reads content from the connected socket.
- * @return the content read.
- */
- public String read(){
- return this.reader.nextLine();
- }
- /**
- * Close the connection.
- * @throws java.io.IOException
- */
- public void close() throws java.io.IOException {
- this.reader.close();
- this.writer.close();
- this.socket.close();
- }
- public boolean isConnected (){
- return !(this.socket.isInputShutdown() && this.socket.isOutputShutdown());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement