TCP: Server端
try {
ServerSocket ss = new ServerSocket(8808);
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.print("hello");
pw.flush();
pw.close();
socket.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
Client端:
try {
Socket socket = new Socket("localhost",8808);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
System.out.println(str);
}catch (IOException e) {
e.printStackTrace();
}
这样就简单实现来服务器端与客户端的socket数据传输。
UDP Server端:
try {
DatagramSocket ds = new DatagramSocket(9999); // 创建数据socket
byte[] buff = new byte[1024];
DatagramPacket dp = new DatagramPacket(buff,1024);// 创建数据包
ds.receive(dp); // 接受数据
String str = new String(dp.getData()); // 得到数据
System.out.println(str);
ds.close();
} catch (Exception e) {
e.printStackTrace();
}
Client端:
DatagramSocket ds = new DatagramSocket(9998);// 创建数据socket
String str = "abc"; // 要发送的数据
DatagramPacket dp = new DatagramPacket(
str.getBytes(),0,str.length(),
InetAddress.getByName("localhost"),9999);
// 创建数据包
ds.send(dp); // 发送数据
ds.close();
TCP通信的服务器端创建一个多线程模型
public class TestServerThread {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8808);
Socket socket = null;
if ((socket=ss.accept()) != null) {
new MyThread(socket).start();
}
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyThread extends Thread{
private Socket socket;
public MyThread(Socket socket){
super();
this.socket = socket;
}
public void run(){
try {
try {
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.print("new is :" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
pw.flush();
pw.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
一般的WEB服务器都支持多线程,WEB服务器都是用到这些基础知识。我们可以用java 的TCP变成API创建一个very简单的WEB服务器,如果真的想开发出像Tomcat,WEBSphere确实不是很简单的事情。
pw.print("<html><head><title>title</title></head><body>hello welcome!</body></html>");
运行main 然后打开浏览器输入http://localhost:8808 这样就可以在浏览器看到hellol welcome啦。
最简单的模拟啦web服务器。像tomcat等服务器实现的协议不知道有多少种。做java ee开发就不做深究。