标签:sys localhost stream exception tin stack put shutdown input
UDP传输
public class UDPSend { public static void main(String[] args) throws IOException { InetAddress ina=InetAddress.getLocalHost(); byte[] bytes="你好吗".getBytes(); DatagramSocket ds=new DatagramSocket(); DatagramPacket dp=new DatagramPacket(bytes, bytes.length,ina, 9528); ds.send(dp); ds.close(); } }
UDP的接收
public class UDPRecieve { public static void main(String[] args) throws IOException { DatagramSocket ds=new DatagramSocket(9528); byte[] buf=new byte[1024]; int len=buf.length; DatagramPacket dp=new DatagramPacket(buf, len); ds.receive(dp); System.out.println(new String(buf,0,len)); ds.close(); } }
TCP的客户端
public class TCPClient { public static void main(String[] args) throws IOException, IOException { Socket socket=new Socket("192.168.1.123",3001); OutputStream os=socket.getOutputStream(); FileInputStream fis=new FileInputStream("C:\\Users\\Rui\\Desktop\\read\\天际势力图.jpg"); int len=0; byte[] bytes=new byte[1024]; while((len=fis.read(bytes))!=-1){ os.write(bytes); } socket.shutdownOutput(); InputStream in=socket.getInputStream(); len=in.read(bytes); System.out.println(new String(bytes,0,len)); fis.close(); socket.close(); } }
TCP的服务器端
public class TCPServer { public static void main(String[] args) throws IOException { ServerSocket server =new ServerSocket(7757); Socket socket=server.accept(); InputStream in=socket.getInputStream(); int len=0; byte[]bytes=new byte[1024]; File f=new File("C:\\Users\\Rui\\Desktop\\write\\write\\tnt.jpg"); FileOutputStream out=new FileOutputStream(f); while((len=in.read(bytes))!=-1){ out.write(bytes, 0, len); } OutputStream os=socket.getOutputStream(); os.write("传入成功".getBytes()); out.close(); socket.close(); server.close(); } }
TCP多线程接收信息的Runnable实现类
public class UPload implements Runnable { private Socket socket; private FileOutputStream out; UPload(Socket socket){ this.socket=socket; } public void run() { InputStream in; try { in = socket.getInputStream(); int len=0; byte[]bytes=new byte[1024]; File f=new File("C:\\Users\\Rui\\Desktop\\write\\write\\tnt.jpg"); FileOutputStream out=new FileOutputStream(f); while((len=in.read(bytes))!=-1){ out.write(bytes, 0, len); } OutputStream os=socket.getOutputStream(); os.write("传入成功".getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
标签:sys localhost stream exception tin stack put shutdown input
原文地址:https://www.cnblogs.com/zhangrui0328/p/9242613.html