Created
February 28, 2019 13:49
-
-
Save SatyaSnehith/52b1ac7edec2cc3e8179ec0a478b3c1b to your computer and use it in GitHub Desktop.
Acts as Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sample; | |
import java.awt.*; | |
import java.io.*; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
public class Connection extends Thread { | |
final int PORT = 12345; | |
private boolean isRunning = true; | |
ReadWriteThread readWriteThread; | |
ServerSocket serverSocket; | |
ReadWriteThread.ReadWriteListener readWriteListener; | |
void setReadWriteListener(ReadWriteThread.ReadWriteListener readWriteListener) { | |
this.readWriteListener = readWriteListener; | |
} | |
@Override | |
public void run() { | |
try { | |
serverSocket = new ServerSocket(PORT); | |
System.out.println("Server Started.."); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
while(isRunning) { | |
try { | |
Socket socket = serverSocket.accept(); | |
readWriteThread = new ReadWriteThread(socket.getInputStream(), socket.getOutputStream()); | |
readWriteThread.setReadWriteListener(readWriteListener); | |
readWriteThread.start(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public void terminate() { | |
isRunning = false; | |
// interrupt(); | |
} | |
} | |
class ReadWriteThread extends Thread { | |
boolean isRunning = true; | |
InputStream inputStream; | |
OutputStream outputStream; | |
BufferedReader reader; | |
BufferedWriter writer; | |
ReadWriteListener readWriteListener; | |
ReadWriteThread(InputStream inputStream, OutputStream outputStream) { | |
this.inputStream = inputStream; | |
this.outputStream = outputStream; | |
} | |
void stopRunning() { | |
isRunning = false; | |
interrupt(); | |
} | |
void setReadWriteListener(ReadWriteListener readListener) { | |
this.readWriteListener = readWriteListener; | |
} | |
@Override | |
public void run() { | |
reader = new BufferedReader(new InputStreamReader(inputStream)); | |
writer = new BufferedWriter(new OutputStreamWriter(outputStream)); | |
try { | |
// for(line = ; line != null; line = reader.readLine()) { | |
String r = reader.readLine(); | |
String n = readWriteListener.listener(r); | |
writer.write(n); | |
writer.flush(); | |
writer.close(); | |
System.out.println("ASKMESSAGE:" + r + "REPLYMESSAGE:" + n); | |
// } | |
reader.close(); | |
} catch (Exception e) { | |
} | |
} | |
interface ReadWriteListener { | |
String listener(String msg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment