Skip to content

Instantly share code, notes, and snippets.

@ZhanruiLiang
Created October 9, 2012 04:28
Show Gist options
  • Save ZhanruiLiang/3856598 to your computer and use it in GitHub Desktop.
Save ZhanruiLiang/3856598 to your computer and use it in GitHub Desktop.
Java Socket exp
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.NoSuchElementException;
public class MyServer{
ServerSocket serverSocket;
Socket clientSocket;
Scanner in;
BufferedWriter out;
public void start(){
try{
// create a server
serverSocket = new ServerSocket(8889, 5);
while(true){
// accept a client
log("Waiting for client...");
clientSocket = serverSocket.accept();
log(String.format("Accepted client: %s",
clientSocket.getInetAddress().getHostName()));
// build stream
in = new Scanner(
clientSocket.getInputStream());
out = new BufferedWriter(
new OutputStreamWriter(
clientSocket.getOutputStream()));
while(true){
// read message from client
try{
String msg = recv();
if(msg == null){
break;
}
}catch(IOException ex){
//pass
break;
}
}
log("Client quit.");
}
}catch(IOException ex){
ex.printStackTrace();
}
}
String recv() throws IOException{
String msg;
try{
msg = in.nextLine();
}catch(NoSuchElementException ex){
return null;
}
log(String.format("Received: [%s]", msg));
// reply
out.write("ok\n");
out.flush();
return msg;
}
void log(String s){
System.out.println(s);
}
static public void main(String[] args){
MyServer server = new MyServer();
server.start();
}
};
/*
Reference:
socket example:
http://zerioh.tripod.com/ressources/sockets.html
java document:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
http://docs.oracle.com/javase/1.4.2/docs/api/java/net/ServerSocket.html
http://docs.oracle.com/javase/1.4.2/docs/api/java/net/Socket.html#bind%28java.net.SocketAddress%29
search engine:
www.yahoo.com
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment