java例程练习(网络编程[简单网络连接试验])

import java.net.*;
import java.io.*;

public class TestTCPServer {
	public static void main(String[] args) {
		try {
			ServerSocket ss = new ServerSocket(6666);//阻塞式的
			
			while(true) {
				
				//未经行异常处理!
//			Socket s = ss.accept();
//			DataInputStream dis = 
//				new DataInputStream(s.getInputStream());
//			System.out.println(dis.readUTF());//也是阻塞式的
//			dis.close();
//			s.close();
				
				Socket s1 = ss.accept();
				OutputStream os = s1.getOutputStream();
				DataOutputStream dos = new DataOutputStream(os);
				dos.writeUTF("Hello," + s1.getInetAddress() + 
							"port#" + s1.getPort()+ " bye-bye!");
				
				dos.close();
				s1.close();
				
				
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("程序运行出错:  " + e);
		}
		
		
		
	}
}
import java.net.*;
import java.io.*;
public class TestTCPClient {
	public static void main(String[] args) {
		try {
			Socket s = new Socket("127.0.0.1", 6666);
			//未经行异常处理!
//			OutputStream os = s.getOutputStream();
//			DataOutputStream dos = new DataOutputStream(os);
//			
//			Thread.sleep(3000);
//			dos.writeUTF("Hello Server!");
//			dos.flush();
//			dos.close();
//			s.close();
			
			InputStream is = s.getInputStream();
			DataInputStream dis = new DataInputStream(is);
			System.out.println(dis.readUTF());
			dis.close();
			s.close();
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}


posted on 2012-05-06 12:46  Yours风之恋  阅读(184)  评论(0编辑  收藏  举报