java TCPSocket编程 简单示例

/*
 * 写Socket程序时,应该server端和client端一起写
 * 运行时先运行server端再运行client端
 * 这种方法只是示例单线程阻塞式缺陷很大
 */
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

	public static void main(String[] args) throws Exception {
		ServerSocket ss = new ServerSocket(6666);
		while (true) {
			Socket s = ss.accept(); // accept阻塞式的方法
System.out.println("a client connection");
			DataInputStream dis = new DataInputStream(s.getInputStream());
			System.out.println(dis.readUTF()); // readUTF阻塞式的方法
			dis.close();
			s.close();
		}
	}

}



import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;


public class TCPClient {

	public static void main(String[] args) throws Exception {
		Socket s = new Socket("127.0.0.1",6666);
		OutputStream os = s.getOutputStream();
		DataOutputStream dos = new DataOutputStream(os);
		dos.writeUTF("hello server");
		dos.flush();
		dos.close();
		s.close();
	}

}

你可能感兴趣的:(自己用)