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

java例程练习(网络编程[简单双向通信试验])

 
阅读更多
import java.net.*;
import java.io.*;

public class TestTCPServer {
	public static void main(String[] args) {
		InputStream in = null;
		OutputStream out = null;
		
		try {
			ServerSocket ss  = new ServerSocket(8888);
			Socket socket = ss.accept();
			in = socket.getInputStream();
			out = socket.getOutputStream();
			
			DataInputStream dis = new DataInputStream(in);
			DataOutputStream dos = new DataOutputStream(out);
			String s = null;
			
			if((s = dis.readUTF()) != null) {
				System.out.println(s);
				System.out.println("form:" + socket.getInetAddress());
				System.out.println("port:" + socket.getPort());
			}
			
			dos.writeUTF("Hi, hello");
			dis.close();
			dos.close();
			socket.close();
			
			
		} catch(IOException e) {
			e.printStackTrace();
		}
		
	}
}
import java.net.*;
import java.io.*;
public class TestTCPClient {
	public static void main(String[] args) {
		InputStream in = null;
		OutputStream out = null;
		
		try {
			
			Socket socket = new Socket("localhost", 8888);
			in = socket.getInputStream();
			out = socket.getOutputStream();
			
			DataInputStream dis = new DataInputStream(in);
			DataOutputStream dos = new DataOutputStream(out);
			
			dos.writeUTF("Hey");
			
			String s = null;
			
			if((s = dis.readUTF()) != null) {
				System.out.println(s);
			}
			
			
			dis.close();
			dos.close();
			socket.close();
				
		} catch(UnknownHostException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		
	}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics