客户端
连接服务器 Socket
发送消息
package com.Internetlearn.TCP.interactive; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; public class ClientTCP { public static void main(String[] args) { Socket socket = null; OutputStream os = null; try { //要知道服务器地址 端口号 InetAddress serverIP = InetAddress.getByName("127.0.0.1"); int port = 9990; //创建一个socket连接 socket = new Socket(serverIP,port); //发送消息 IO流 os = socket.getOutputStream(); os.write("发送消息".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { try { os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
服务器端
建立服务器的端口ServerSocket
等待用户的连接 accept
接受用户的消息
package com.Internetlearn.TCP.interactive; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerTCP { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { //我有一个地址 serverSocket = new ServerSocket(9990); //等待客户端连接 socket = serverSocket.accept(); //读取客户端消息 is = socket.getInputStream(); /* 暴力读取 byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer))!=-1){ String message = new String(buffer,0,len); System.out.println(message); } */ //管道流 baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while(-1 != (len = is.read(buffer))){ baos.write(buffer,0,len); } System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); } finally { try { baos.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
注意点
一端退出,但退出时并未关闭该连接,另一端如果在从连接中读数据则抛出该异常(Connection reset)。简单的说就是在连接断开后的读和写操作引起的。
服务器端
package com.Internetlearn.TCP.File; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class FileServer { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; FileOutputStream fos = null; OutputStream os = null; try { //创建服务 serverSocket = new ServerSocket(9000); //监听客户端的连接 socket = serverSocket.accept(); //获取输入流 is = socket.getInputStream(); //文件输出流 fos = new FileOutputStream(new File("receive.txt")); byte[] buffer = new byte[1024]; int len; while(-1!=(len = is.read(buffer))){ fos.write(buffer,0,len); } //通知客户端接收完毕 os = socket.getOutputStream(); os.write("接收完毕".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { // try{ os.close(); fos.close(); is.close(); socket.close(); serverSocket.close(); } catch (Exception e) { e.printStackTrace(); } } } }
客户端
package com.Internetlearn.TCP.File; import java.io.*; import java.net.InetAddress; import java.net.Socket; public class FileClient { public static void main(String[] args) { Socket socket = null; OutputStream os = null; FileInputStream fis = null; InputStream is = null; ByteArrayOutputStream baos = null; try { //创建Socket连接 socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000); //创建输出流 os = socket.getOutputStream(); //文件流 fis = new FileInputStream(new File("hamlet.txt")); //读文件 byte[] inbuffer = new byte[1024]; int inlen; while ((inlen=fis.read(inbuffer))!=-1){ os.write(inbuffer,0,inlen); } //通知服务器我已经发送完了 socket.shutdownOutput(); //确认服务器端接收完毕 is = socket.getInputStream(); baos = new ByteArrayOutputStream(); byte[] outbuffer = new byte[1024]; int outlen; while((outlen = is.read(outbuffer))!=-1){ baos.write(outbuffer,0,outlen); } System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); } finally { //关闭资源 try { baos.close(); is.close(); fis.close(); os.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } } }
不需要连接,需要知道对方地址
发送端
package com.Internetlearn.UDP; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.nio.file.LinkPermission; //不需要连接服务器 public class UDPClient { public static void main(String[] args) { DatagramSocket datagramSocket = null; try { //建立一个socket datagramSocket = new DatagramSocket(); //建个包 String message = "你好!"; //发送给谁 IP + 端口 InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); int port = 9090; //数据 数据初始位置 数据长度 发送给谁 (IP + 端口) DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(),0,message.getBytes().length,inetAddress,port); //发送包 datagramSocket.send(datagramPacket); } catch (Exception e) { e.printStackTrace(); } finally { datagramSocket.close(); } } }
接收端
package com.Internetlearn.UDP; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPServer { public static void main(String[] args) { DatagramSocket datagramSocket = null; try { //开放端口(端口号) datagramSocket = new DatagramSocket(9090); //创建接收数据包 byte[] buffer = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length); //接收包 datagramSocket.receive(datagramPacket); //数据显示 System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength())); } catch (Exception e) { e.printStackTrace(); } finally { datagramSocket.close(); } } }
发送端线程
package com.Internetlearn.UDP.Chat; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.*; public class TalkSend implements Runnable { /** * When an object implementing interface {@code Runnable} is used * to create a thread, starting the thread causes the object's * {@code run} method to be called in that separately executing * thread. ** The general contract of the method {@code run} is that it may * take any action whatsoever. * * @see Thread#run() */ DatagramSocket datagramSocket = null; BufferedReader bufferedReader = null; private int fromPort;//自身端口 private String toIP; //目标IP private int toPort; //目标端口 public TalkSend(int fromPort, String toIP, int toPort) { this.fromPort = fromPort; this.toIP = toIP; this.toPort = toPort; try { datagramSocket = new DatagramSocket(fromPort); //控制台获取message bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } catch (SocketException e) { e.printStackTrace(); } } @Override public void run() { while(true){ try { String message = bufferedReader.readLine(); DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(), 0,message.getBytes().length,new InetSocketAddress(this.toIP,this.toPort)); datagramSocket.send(datagramPacket); //通话结束标志 if("bye".equals(message)){ break; } } catch (Exception e) { e.printStackTrace(); } finally { datagramSocket.close(); } } } }
接收端线程
package com.Internetlearn.UDP.Chat; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class TalkReceive implements Runnable { /** * When an object implementing interface {@code Runnable} is used * to create a thread, starting the thread causes the object's * {@code run} method to be called in that separately executing * thread. ** The general contract of the method {@code run} is that it may * take any action whatsoever. * * @see Thread#run() */ DatagramSocket datagramSocket = null; private int port; public TalkReceive(int port) { this.port = port; try { datagramSocket = new DatagramSocket(port); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { while (true){ try { //创建接收数据包 byte[] buffer = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length); //接收包 datagramSocket.receive(datagramPacket); //数据显示 String message = new String(datagramPacket.getData(), 0, datagramPacket.getLength()); System.out.println(message); //通话结束标志 if("bye".equals(message)){ break; } } catch (Exception e) { e.printStackTrace(); } finally { datagramSocket.close(); } } } }