Created
April 27, 2013 08:36
-
-
Save chuanxd/5472351 to your computer and use it in GitHub Desktop.
Java basic client server linking program on command line. Server [port_number] Client [ip_address] [port_number]
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.io.*; | |
import java.net.*; | |
public class Client { | |
int i; | |
static String iaddr; | |
static int port; | |
public Client() { | |
try{ | |
Socket socket=new Socket(InetAddress.getByName(iaddr),port); | |
DataOutputStream outstream = new DataOutputStream(socket.getOutputStream()); | |
InputStreamReader isr = new InputStreamReader(System.in); | |
BufferedReader br = new BufferedReader(isr); | |
System.out.println("Input data on keyboard..."); | |
while(true) { | |
i = br.read(); | |
outstream.writeInt(i); | |
} | |
} | |
catch(IOException e){ | |
System.out.println(e.getMessage()); | |
} | |
} | |
public static void main(String args[]) { | |
if (args.length < 2){ | |
System.out.println("USAGE: java Client [iaddr] [port]"); | |
System.exit(1); | |
} | |
iaddr= args[0]; | |
port=Integer.parseInt(args[1]); | |
Client ClientStart=new Client(); | |
} | |
} |
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 Server { | |
Socket socket; | |
static int port; | |
int messagein; | |
public Server() { | |
try{ | |
ServerSocket SS = new ServerSocket(port); | |
System.out.println("Server is created and waiting Client to connect..."); | |
Socket socket = SS.accept(); | |
System.out.println("Client IP = " + | |
socket.getInetAddress().getHostAddress()); | |
DataInputStream instream = new DataInputStream(socket.getInputStream()); | |
while(true) { | |
messagein = instream.readInt(); | |
System.out.print((char)messagein); | |
} | |
} | |
catch(IOException e){ | |
System.out.println(e.getMessage()); | |
} | |
} | |
public static void main(String args[]){ | |
if(args.length < 1){ | |
System.out.println("Usage: java Server [port]"); | |
System.exit(1); | |
} | |
port=Integer.parseInt(args[0]); | |
Server ServerStart=new Server(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment