java 网络协议(一)Tcp多线程服务器端编程

1,通用服务器代码
package multiThread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
//通用多线程服务器?????????????????
public class MTServerBase extends Thread {

	// client
	protected Socket socket;

	// Here is the thread that does the work
	// Presumably you'll override this in the subclass
	public void run() {
		try {
			String s = "I'm a test server. Goodbye";
			socket.getOutputStream().write(s.getBytes()); //发送给客户端
			
			byte[] b = new byte[40]; //读客户端
			socket.getInputStream().read(b);
			System.out.println("服务器端显示:"+new String(b));
			socket.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	 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...");
					// create new MTServerBase or subclass
					MTServerBase t = (MTServerBase) clobj.newInstance();
					t.socket = esock;
					t.start();
				} catch (Exception e) {
					try {
						esock.close();
					} catch (Exception ec) {
					}
				}
			}
		} catch (IOException e) {
		}
		// if we return something is wrong!
	}
//test main simple
	public static void main(String[] args) {
		System.out.println("Starting server on port 1234");
		MTServerBase.startServer(1234, MTServerBase.class);
	}
}

可以直接用telnet客户端测试





或者测试的客户端程序:
package multiThread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket socket = new Socket("localhost",1234);
		
		InputStream is = socket.getInputStream();
		OutputStream out = socket.getOutputStream();
		
		byte[] b = new byte[40];
		is.read(b);
		String data = new String(b);
		System.out.println("客户端显示:"+data);
		out.write(("from client:"+data).getBytes()); //返回服务器
		is.close();
		socket.close();
	}
}





2,利用1所写的基类,实现一个特殊的server
package multiThread;
import java.io.*;
//使用基类组成另一个服务器的例子,将基类MTServerBase的main函数注释掉
public class UCServer extends MTServerBase {
//socket是父类中继承来的,代表客户端
	public void run() {
		try {
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();
			while (true) {
				char c = (char) is.read();
				// end on Control+C or Control+D
				if (c == '\003' || c == '\004')
					break;
				os.write(Character.toUpperCase(c)); //为啥是返回telnet端,应该是服务器端才是啊????
			}
			socket.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	public static void main(String[] args) {//参数为端口号
		int n = Integer.parseInt(args[0]);
		System.out.println("Starting server on port " + n);
		startServer(n, UCServer.class);

	}
}

telnet端输入的字母,返回为大写的字母






你可能感兴趣的:(java,多线程,编程,socket,网络协议)