Advertisement
Guest User

Untitled

a guest
Aug 19th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. public class GameClient {
  2. private Socket socket;
  3. private String serverIP;
  4. private OutputStreamWriter writer;
  5. private BufferedReader reader;
  6.  
  7. public GameClient(String host){
  8. this.serverIP = host;
  9.  
  10. try{
  11. //Connect to server
  12. socket = new Socket(InetAddress.getByName(serverIP), 1234);
  13. writer = new OutputStreamWriter(this.socket.getOutputStream(), "UTF-8");
  14. reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "UTF-8"));
  15. //Start a new thread for reading from server
  16. new Thread(new GameClientReader(socket)).start();
  17.  
  18. Scanner scanner = new Scanner(System.in);
  19. System.out.println("Write something: ");
  20. String str = "";
  21. // while((str = scanner.nextLine()) != null){
  22. // writer.write(str);
  23. // writer.write('n');
  24. // writer.flush();
  25. // System.out.println("Write something: ");
  26. // }
  27.  
  28. }catch(IOException e){
  29. System.out.println("Client failed to connect!");
  30. e.printStackTrace();
  31. }finally{
  32. try {
  33. socket.close();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }
  39.  
  40.  
  41. public void send(JSONObject json){
  42. try{
  43. String message = json.toJSONString();
  44. writer.write(message);
  45. writer.write('n');
  46. writer.flush();
  47. }catch(IOException e){
  48. e.printStackTrace();
  49. }
  50. }
  51.  
  52. public void send(String msg){
  53. try {
  54. writer.write(msg);
  55. writer.flush();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60.  
  61. public static void main(String args[]){
  62. GameClient client = new GameClient("127.0.0.1");
  63.  
  64. Scanner scanner = new Scanner(System.in);
  65. System.out.println("Write something: ");
  66. String str = "";
  67. while((str = scanner.nextLine()) != null){
  68. client.send(str);
  69. System.out.println("Write something: ");
  70. }
  71.  
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement