java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

java使用Socket 编写一个Server

理解socket

java的socket中的ServerSocket提供固定位置的访问。比如我们访问一个服务器http://java-er.com 其实是对java-er.com这台机器上固定80端口的访问。

下面看个小例子。这个例子你在Eclipse里启动这个程序,就可以在浏览器里直接访问并会有数据打印在浏览器上。

package com.javaer.examples.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("server start");
		ServerSocket server = new ServerSocket(2156);
		Socket client = server.accept();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				client.getInputStream()));
		PrintWriter out = new PrintWriter(client.getOutputStream());
		
		int i = 0;
		
		while (true) {
			String str = in.readLine();//接受客户方输入字符串
			System.out.println(str);
			i++;
			out.println("has receive...." + i);//回传给客户端
			out.flush();
			if(str.indexOf("Accept-Charset:")!=-1){ //用于网页请求鉴定
				break;
			}
			if (str.equals("end"))//接收到客户端输入end, 表示停止回话
				break;
		}
		
		client.close();
	}

}

启动以后,在浏览器里输入http://localhost:2156

浏览器里返回

Eclipse后台返回

GET / HTTP/1.1
Host: localhost:2156
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3

你懂了吗?


This entry was posted in JAVA and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-socket-server/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply