Created
November 29, 2017 11:25
-
-
Save xtpor/ba53a58e8705bfa61f129062dd3664c2 to your computer and use it in GitHub Desktop.
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.net.*; | |
import java.io.*; | |
import java.util.*; | |
public class EchoClient { | |
public static void main(String[] args) throws IOException { | |
Scanner scanner = new Scanner(System.in); | |
System.out.println("Connecting to server ..."); | |
Socket sock = new Socket("localhost", 12345); | |
DataInputStream in = new DataInputStream(sock.getInputStream()); | |
DataOutputStream out = new DataOutputStream(sock.getOutputStream()); | |
System.out.println("Connected."); | |
int i = scanner.nextInt(); | |
out.writeInt(i); | |
int result = in.readInt(); | |
System.out.println(result); | |
} | |
} |
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.net.*; | |
import java.io.*; | |
public class EchoServer { | |
public static void main(String[] args) { | |
try { | |
ServerSocket serverSock = new ServerSocket(12345); | |
while (true) { | |
Socket conn = serverSock.accept(); | |
new ClientThread(conn).start(); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
class ClientThread extends Thread { | |
private Socket sock; | |
public ClientThread(Socket sock) { | |
this.sock = sock; | |
} | |
public void run() { | |
try { | |
DataInputStream in = new DataInputStream(sock.getInputStream()); | |
DataOutputStream out = new DataOutputStream(sock.getOutputStream()); | |
int number = (int) Math.floor(Math.random() * 100); | |
int failedAttempts = 0; | |
while (true) { | |
if (failedAttempts >= 5) { | |
break; | |
} | |
int input = in.readInt(); | |
if (input > number) { | |
out.writeUTF("your number is too big"); | |
failedAttempts += 1; | |
} else if (input < number) { | |
out.writeUTF("your number is too small"); | |
failedAttempts += 1; | |
} else { | |
break; | |
} | |
} | |
if (failedAttempts < 5) { | |
out.writeUTF("yes, you have got the right number"); | |
} else { | |
out.writeUTF("Sorry you have failed 5 times"); | |
} | |
in.close(); | |
out.close(); | |
sock.close(); | |
} catch (EOFException e) { | |
} catch (IOException e) { | |
} | |
} | |
public static int factorial(int n) { | |
if (n == 0) { | |
return 1; | |
} else { | |
return n * factorial(n - 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment