Created
          October 9, 2012 04:33 
        
      - 
      
- 
        Save ZhanruiLiang/3856619 to your computer and use it in GitHub Desktop. 
    Java Socket exp(Client)
  
        
  
    
      This file contains hidden or 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 MyClient{ | |
| Socket clientSocket; | |
| OutputStreamWriter out; | |
| Scanner in; | |
| public void connect(String dest, int port){ | |
| try{ | |
| // connect to a server | |
| clientSocket = new Socket(dest, port); | |
| log(String.format("Connected to server: %s", dest)); | |
| // build stream | |
| in = new Scanner(clientSocket.getInputStream()); | |
| out = new OutputStreamWriter(clientSocket.getOutputStream()); | |
| for(int i = 0; i < 12; i++){ | |
| send(String.format("msg#%d", i)); | |
| } | |
| }catch(IOException ex){ | |
| ex.printStackTrace(); | |
| } | |
| } | |
| String send(String msg) throws IOException{ | |
| out.write(msg + "\n"); | |
| out.flush(); | |
| log(String.format("Sent: [%s]", msg)); | |
| String recv = in.nextLine(); | |
| log(String.format("Received: [%s]", recv)); | |
| return recv; | |
| } | |
| void log(String s){ | |
| System.out.println(s); | |
| } | |
| static public void main(String[] args){ | |
| MyClient client = new MyClient(); | |
| if(args.length == 0){ | |
| client.connect("localhost", 8889); | |
| }else{ | |
| client.connect(args[0], Integer.parseInt(args[1])); | |
| } | |
| } | |
| }; | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment