android之Socket
服务器端的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){
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。