第一个java网络编程
服务端
import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.Date; public class TcpC { public static void main(String[] args) { Socket socket = null; OutputStream os = null; try { InetAddress serverip = InetAddress.getByName("127.0.0.1"); int port = 9999; socket = new Socket(serverip,port); os =socket.getOutputStream(); os.write("第一个网络编程".getBytes()); }catch (IOException e){ e.printStackTrace(); }finally { if (os!=null){ try { os.close(); }catch (IOException e){ e.printStackTrace(); } if (socket!=null){ try { socket.close(); }catch (IOException e){ e.printStackTrace(); } } } } } }
上传图片
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class serverFile { public static void main(String[] args) throws IOException { ServerSocket serverS = new ServerSocket(6666); Socket socket = serverS.accept(); InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("D:\\myDoc2\\"+"gdg.jpg")); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer))!=-1){ fos.write(buffer,0,len); } fos.close(); is.close(); socket.close(); serverS.close(); } }
客户端
import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.Date; public class TcpC { public static void main(String[] args) { Socket socket = null; OutputStream os = null; try { InetAddress serverip = InetAddress.getByName("127.0.0.1"); int port = 9999; socket = new Socket(serverip,port); os =socket.getOutputStream(); os.write("第一个网络编程".getBytes()); }catch (IOException e){ e.printStackTrace(); }finally { if (os!=null){ try { os.close(); }catch (IOException e){ e.printStackTrace(); } if (socket!=null){ try { socket.close(); }catch (IOException e){ e.printStackTrace(); } } } } } }