一個java的TCP通信例子

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

class server{
	
	public static void main(String[] args)throws Exception{
		ServerSocket ss =new ServerSocket(10000);
		while(true){
			Socket s = ss.accept();
			String ip = s.getInetAddress().getHostAddress();
			InputStream in = s.getInputStream();
			byte[] buff = new byte[1024];
			int len = in.read(buff);
			String data = new String(buff,0,len);
			System.out.println(ip+"::"+data);
			
			OutputStream out = s.getOutputStream();
			out.write("server lai le".getBytes());
			s.close();
		}
	}
}

class client{
	public static void main(String[] args)throws Exception{
		Socket s = new Socket("localhost",10000);
		OutputStream out = s.getOutputStream();
		out.write("client lai le".getBytes());
		
		InputStream in = s.getInputStream();
		byte[] buff = new byte[1024];
		int len = in.read(buff);
		String data = new String(buff,0,len);
		System.out.println("server::"+data);
		s.close();
	}
}

發佈了31 篇原創文章 · 獲贊 40 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章