Last active
November 9, 2018 14:39
-
-
Save SatyaSnehith/253fba6603046f58c59e0e8652644cd2 to your computer and use it in GitHub Desktop.
This Server accepts requests and sends information
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
import java.io.*; | |
import java.net.*; | |
import java.util.Scanner; | |
public class Server { | |
private ServerSocket serverSocket = null; | |
private Socket socket = null; | |
private ServerThread serverThread; | |
Server(int port) { | |
try { | |
serverSocket = new ServerSocket(); | |
InetSocketAddress address = new InetSocketAddress(port); | |
serverSocket.bind(address); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static void main(String[] args) { | |
Server server = new Server(1234); | |
server.startServer(); | |
} | |
public void startServer() { | |
serverThread = new ServerThread(serverSocket); | |
serverThread.start(); | |
} | |
public void stoprServer() { | |
try { | |
serverSocket.close(); | |
Thread.interrupted(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
class ServerThread extends Thread { | |
private ServerSocket serverSocket; | |
private boolean running = true; | |
ServerThread(ServerSocket serverSocket) { | |
this.serverSocket = serverSocket; | |
} | |
public void stopRunning() { | |
running = false; | |
} | |
public void run() { | |
while (running) { | |
try { | |
socket = serverSocket.accept(); | |
SocketThread socketThread = new SocketThread(socket); | |
socketThread.start(); | |
socketThread.setReadListener(new ReadListener() { | |
@Override | |
public String read(String string) { | |
System.out.println(string); | |
return "information about " + string; | |
} | |
}); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
class SocketThread extends Thread { | |
private BufferedReader br; | |
private ReadListener readListener; | |
private Writer writer; | |
private Socket socket; | |
SocketThread(Socket socket) { | |
this.socket = socket; | |
} | |
void setReadListener(ReadListener readListener) { | |
this.readListener = readListener; | |
} | |
public void run() { | |
try { | |
InputStream is = socket.getInputStream(); | |
OutputStream os = socket.getOutputStream(); | |
writer = new OutputStreamWriter(os, "ASCII"); | |
br = new BufferedReader(new InputStreamReader(is)); | |
String string = ""; | |
if ((string = br.readLine()) != null) { | |
writer.write(readListener.read(string)); | |
writer.flush(); | |
writer.close(); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
interface ReadListener { | |
public String read(String string); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment