`
txf2004
  • 浏览: 6866621 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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();
		}
		
	}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics