Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class GameClient {
- private Socket socket;
- private String serverIP;
- private OutputStreamWriter writer;
- private BufferedReader reader;
- public GameClient(String host){
- this.serverIP = host;
- try{
- //Connect to server
- socket = new Socket(InetAddress.getByName(serverIP), 1234);
- writer = new OutputStreamWriter(this.socket.getOutputStream(), "UTF-8");
- reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "UTF-8"));
- //Start a new thread for reading from server
- new Thread(new GameClientReader(socket)).start();
- Scanner scanner = new Scanner(System.in);
- System.out.println("Write something: ");
- String str = "";
- // while((str = scanner.nextLine()) != null){
- // writer.write(str);
- // writer.write('n');
- // writer.flush();
- // System.out.println("Write something: ");
- // }
- }catch(IOException e){
- System.out.println("Client failed to connect!");
- e.printStackTrace();
- }finally{
- try {
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public void send(JSONObject json){
- try{
- String message = json.toJSONString();
- writer.write(message);
- writer.write('n');
- writer.flush();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- public void send(String msg){
- try {
- writer.write(msg);
- writer.flush();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static void main(String args[]){
- GameClient client = new GameClient("127.0.0.1");
- Scanner scanner = new Scanner(System.in);
- System.out.println("Write something: ");
- String str = "";
- while((str = scanner.nextLine()) != null){
- client.send(str);
- System.out.println("Write something: ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement