服务器端的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(); }
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(); } }
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){
原文:http://blog.csdn.net/a8903289/article/details/43541567