As practice I wanted to write a Socket in Java:
/* User: koray@tugay.biz Date: 21/02/15 Time: 13:30 */
import java.io.IOException;
import java.net.ServerSocket;
public class MyServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
new Thread(new ServerSocketThread(serverSocket.accept())).start();
}
}
}
and the rest of it:
/* User: koray@tugay.biz Date: 21/02/15 Time: 18:14 */
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ServerSocketThread implements Runnable {
Socket socket;
public ServerSocketThread(Socket accept) {
this.socket = accept;
}
@Override
public void run() {
try {
Scanner s = new Scanner(socket.getInputStream());
String readLine;
while (!(readLine = s.nextLine()).equals("bye")) {
System.out.println(readLine);
}
new PrintWriter(socket.getOutputStream()).write("Bye then..");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I wanted to write it as clean as possible. Any improvements, suggestions?
I can use it like this:
Korays-MacBook-Pro:~ koraytugay$ telnet localhost 8888 Trying ::1... Connected to localhost. Escape character is '^]'. koray tugay asdfako bye Connection closed by foreign host.