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();
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2663687.html