Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android之Socket

android之Socket

編輯:關於Android編程

服務器端的TCP

class ServiceSocket extends Thread{
	   public void run(){
		   ServerSocket serversocket=null;
		   try {
			serversocket =new ServerSocket(7980);
			Socket socket= serversocket.accept();
			InputStream inputs = socket.getInputStream();
			byte[] buffer =new byte[1024];
			int tmp=0;
			while((tmp=inputs.read(buffer))!=-1){
				System.out.println(new String(buffer,0,tmp));
				
				
			}
			
		} catch (IOException e) {
		
			e.printStackTrace();
		}
		   finally{
			   try {
				serversocket.close();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			   
			   
		   }
		   
		   
客戶端TCP

 public static void mian(String[]args){
	  try {
		Socket socket=new Socket("192.168.1.104",7980);
		InputStream inpust =socket.getInputStream();
		byte[]buffer=new byte[1024];
	   int tmp=0;
	   while((tmp=inpust.read(buffer))!=-1){
		   System.out.println(new String(buffer,0,tmp));
		   
	   }
		
	} catch (Exception e) {
		
		e.printStackTrace();
	}

服務器端UDP

ublic class UDP服務器端 {
    class UDPThread extends Thread{
    	public void run(){
    		try {
				DatagramSocket socket=new DatagramSocket(7980);
				byte[] data=new byte[1024];
				//創建一個空的Datagrampcket對象
				DatagramPacket datagrampacket= new DatagramPacket(data, data.length);
				//使用receive方法接受客戶端發送的數據
				socket.receive(datagrampacket);
				System.out.println(datagrampacket.getLength());
				
			} catch (Exception e) {
			
				e.printStackTrace();
			}
    		
    		
    		
    	}
    	
    	

客戶端UDP

public static void main(String[]args){
	try{
		//創建一個DatagramSocket對象
    DatagramSocket socket=new DatagramSocket(7980);
     //創建一個InetAddress對象
    InetAddress sercerAdderess=InetAddress.getByName("192.168.1.104");
    String str="hello";
    byte []data=str.getBytes();
     //創建一個DatagramPacket對象,並指定這個數據包要發送的網絡當中的地址和端口號
    DatagramPacket packet=new DatagramPacket(data, data.length,sercerAdderess,7980);
    
     //調用socket的send方法 發送數據
    socket.send(packet);
    
	}
	catch(Exception e){
		



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved