UDP,TCP与TCP多线程的传输接收
Posted zhangrui0328
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UDP,TCP与TCP多线程的传输接收相关的知识,希望对你有一定的参考价值。
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(); } } }
以上是关于UDP,TCP与TCP多线程的传输接收的主要内容,如果未能解决你的问题,请参考以下文章