首页 > 代码库 > java socket服务器端搭建

java socket服务器端搭建

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;

public class ServerBase extends Thread {

	public static void main(String[] args) {
		ServerBase.startServer(8809, ServerBase.class);
	}

	protected Socket socket;

	public void run() {
		try {
			byte[] b = new byte[100]; 
			socket.getInputStream().read(b);
				byte[] out = { (byte) 0xa7, (byte) 0xcb };
				socket.getOutputStream().write(out);
		
			socket.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	@SuppressWarnings({ "resource", "rawtypes" })
	public static void startServer(int port, Class clobj) {
		ServerSocket ssock;
		try {
			ssock = new ServerSocket(port);
			System.out.println("Listening...");
			while (true) {
				Socket esock = null;
				try {
					esock = ssock.accept();
					System.out.println("connected...");
					ServerBase t = (ServerBase) clobj.newInstance();
					t.socket = esock;
					t.start();
				} catch (Exception e) {
					try {
						esock.close();
					} catch (Exception ec) {
					}
				}
			}
		} catch (IOException e) {
		}
	}

}