简单tcp传输
package pack; /* 演示tcp传输。 1,tcp分客户端和服务端。 2,客户端对应的对象是Socket。 服务端对应的对象是ServerSocket。 客户端, 通过查阅socket对象,发现在该对象建立时,就可以去连接指定主机。 因为tcp是面向连接的。所以在建立socket服务时, 就要有服务端存在,并连接成功。形成通路后,在该通道进行数据的传输。 需求:给服务端发送给一个文本数据。 步骤: 1,创建Socket服务。并指定要连接的主机和端口。 */ import java.io.*; import java.net.*; class TcpClient { public static void main(String[] args) throws Exception { // 创建客户端的socket服务。指定目的主机和端口 Socket s = new Socket("127.0.0.1", 10003); // 为了发送数据,应该获取socket流中的输出流。 OutputStream out = s.getOutputStream(); out.write("tcp ge men lai le ".getBytes()); s.close(); } } /* * 需求:定义端点接收数据并打印在控制台上。 * * 服务端: 1,建立服务端的socket服务。ServerSocket(); 并监听一个端口。 2,获取连接过来的客户端对象。 * 通过ServerSokcet的 accept方法。没有连接就会等,所以这个方法阻塞式的。 * 3,客户端如果发过来数据,那么服务端要使用对应的客户端对象,并获取到该客户端对象的读取流来读取发过来的数据。 并打印在控制台。 * * 4,关闭服务端。(可选) */ class TcpServer { public static void main(String[] args) throws Exception { // 建立服务端socket服务。并监听一个端口。 ServerSocket ss = new ServerSocket(10003); // 通过accept方法获取连接过来的客户端对象。 while (true) { Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip + ".....connected"); // 获取客户端发送过来的数据,那么要使用客户端对象的读取流来读取数据。 InputStream in = s.getInputStream(); byte[] buf = new byte[1024]; int len = in.read(buf); System.out.println(new String(buf, 0, len)); s.close();// 关闭客户端. } // ss.close(); } }
package pack; /* * tcp客户端发送接收 * 字符串转换服务器,客户端发送一个字符串,服务器把字符串转换成大学发送回去. */ import java.io.*; import java.net.*; class TransClient { public static void main(String[] args) throws Exception { Socket s = new Socket("127.0.0.1", 10005); // 定义读取键盘数据的流对象。 BufferedReader bufr = new BufferedReader(new InputStreamReader( System.in)); // 定义目的,将数据写入到socket输出流。发给服务端。 // BufferedWriter bufOut = // new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(), true); // 定义一个socket读取流,读取服务端返回的大写信息。 BufferedReader bufIn = new BufferedReader(new InputStreamReader( s.getInputStream())); String line = null; while ((line = bufr.readLine()) != null) { if ("over".equals(line)) break; out.println(line); // bufOut.write(line); // bufOut.newLine(); // bufOut.flush(); String str = bufIn.readLine(); System.out.println("server:" + str); } bufr.close(); s.close(); } } /* * * 服务端: 源:socket读取流。 目的:socket输出流。 都是文本,装饰。 */ class TransServer { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10005); Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip + "....connected"); // 读取socket读取流中的数据。 BufferedReader bufIn = new BufferedReader(new InputStreamReader( s.getInputStream())); // 目的。socket输出流。将大写数据写入到socket输出流,并发送给客户端。 // BufferedWriter bufOut = // new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(), true); String line = null; while ((line = bufIn.readLine()) != null) { System.out.println(line); out.println(line.toUpperCase()); // bufOut.write(line.toUpperCase()); // bufOut.newLine(); // bufOut.flush(); } s.close(); ss.close(); } } /* * 该例子出现的问题。 现象:客户端和服务端都在莫名的等待。 为什么呢? 因为客户端和服务端都有阻塞式方法。这些方法么没有读到结束标记。那么就一直等 * 而导致两端,都在等待。 */
package pack; import java.io.*; import java.net.*; /** * tcp 上传文件到服务器 */ class TextClient { public static void main(String[] args) throws Exception { Socket s = new Socket("127.0.0.1", 10006); BufferedReader bufr = new BufferedReader(new FileReader("IPDemo.java")); PrintWriter out = new PrintWriter(s.getOutputStream(), true); String line = null; while ((line = bufr.readLine()) != null) { out.println(line); } s.shutdownOutput();// 关闭客户端的输出流。相当于给流中加入一个结束标记-1. BufferedReader bufIn = new BufferedReader(new InputStreamReader( s.getInputStream())); String str = bufIn.readLine(); System.out.println(str); bufr.close(); s.close(); } } class TextServer { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10006); Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip + "....connected"); BufferedReader bufIn = new BufferedReader(new InputStreamReader( s.getInputStream())); PrintWriter out = new PrintWriter(new FileWriter("server.txt"), true); String line = null; while ((line = bufIn.readLine()) != null) { // if("over".equals(line)) // break; out.println(line); } PrintWriter pw = new PrintWriter(s.getOutputStream(), true); pw.println("上传成功"); out.close(); s.close(); ss.close(); } }
package pack; /* tcp上传图片 */ import java.io.*; import java.net.*; class PicClient { public static void main(String[] args) throws Exception { Socket s = new Socket("192.168.1.254", 10007); FileInputStream fis = new FileInputStream("c:\\1.bmp"); OutputStream out = s.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = fis.read(buf)) != -1) { out.write(buf, 0, len); } // 告诉服务端数据已写完 s.shutdownOutput(); InputStream in = s.getInputStream(); byte[] bufIn = new byte[1024]; int num = in.read(bufIn); System.out.println(new String(bufIn, 0, num)); fis.close(); s.close(); } } /* * 服务端 */ class PicServer { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10007); Socket s = ss.accept(); InputStream in = s.getInputStream(); FileOutputStream fos = new FileOutputStream("server.bmp"); byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) != -1) { fos.write(buf, 0, len); } OutputStream out = s.getOutputStream(); out.write("上传成功".getBytes()); fos.close(); s.close(); ss.close(); } }
/* * 上传图片; 服务端多线程接收 */ import java.io.*; import java.net.*; class PicClient { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("请选择一个jpg格式的图片"); return; } File file = new File(args[0]); if (!(file.exists() && file.isFile())) { System.out.println("该文件有问题,要么补存在,要么不是文件"); return; } if (!file.getName().endsWith(".jpg")) { System.out.println("图片格式错误,请重新选择"); return; } if (file.length() > 1024 * 1024 * 5) { System.out.println("文件过大,没安好心"); return; } Socket s = new Socket("192.168.1.254", 10007); FileInputStream fis = new FileInputStream(file); OutputStream out = s.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = fis.read(buf)) != -1) { out.write(buf, 0, len); } // 告诉服务端数据已写完 s.shutdownOutput(); InputStream in = s.getInputStream(); byte[] bufIn = new byte[1024]; int num = in.read(bufIn); System.out.println(new String(bufIn, 0, num)); fis.close(); s.close(); } } /* * 服务端 * * 这个服务端有个局限性。当A客户端连接上以后。被服务端获取到。服务端执行具体流程。 这时B客户端连接,只有等待。 * 因为服务端还没有处理完A客户端的请求,还有循环回来执行下次accept方法。所以 暂时获取不到B客户端对象。 * * 那么为了可以让多个客户端同时并发访问服务端。 那么服务端最好就是将每个客户端封装到一个单独的线程中,这样,就可以同时处理多个客户端请求。 * 如何定义线程呢? * * 只要明确了每一个客户端要在服务端执行的代码即可。将该代码存入run方法中。 */ class PicThread implements Runnable { private Socket s; PicThread(Socket s) { this.s = s; } public void run() { int count = 1; String ip = s.getInetAddress().getHostAddress(); try { System.out.println(ip + "....connected"); InputStream in = s.getInputStream(); File dir = new File("d:\\pic"); File file = new File(dir, ip + "(" + (count) + ")" + ".jpg"); while (file.exists()) file = new File(dir, ip + "(" + (count++) + ")" + ".jpg"); FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) != -1) { fos.write(buf, 0, len); } OutputStream out = s.getOutputStream(); out.write("上传成功".getBytes()); fos.close(); s.close(); } catch (Exception e) { throw new RuntimeException(ip + "上传失败"); } } } class PicServer { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10007); while (true) { Socket s = ss.accept(); new Thread(new PicThread(s)).start(); } // ss.close(); } }
/** * 模拟ie浏览器 访问tomcat服务器 */ class MyIE { public static void main(String[] args)throws Exception { Socket s = new Socket("192.168.1.254",8080); PrintWriter out = new PrintWriter(s.getOutputStream(),true); out.println("GET /myweb/demo.html HTTP/1.1"); out.println("Accept: */*"); out.println("Accept-Language: zh-cn"); out.println("Host: 192.168.1.254:11000"); out.println("Connection: closed"); //这里设置成close,就会结束访问. out.println(); //这里注意要多输出2行 , 这里是存消息体的. out.println(); BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while((line=bufr.readLine())!=null) { System.out.println(line); } s.close(); } } /* http://192.168.1.254:11000/myweb/demo.html GET /myweb/demo.html HTTP/1.1 Accept: application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, i mage/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application /msword, application/QVOD, application/QVOD, Accept-Language: zh-cn Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0 .50727) Host: 192.168.1.254:11000 Connection: Keep-Alive */
/* 简单用户登录,可以有3次机会. */ import java.io.*; import java.net.*; class LoginClient { public static void main(String[] args) throws Exception { Socket s = new Socket("192.168.1.254",10008); BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(s.getOutputStream(),true); BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); for(int x=0; x<3; x++) { String line = bufr.readLine(); if(line==null) break; out.println(line); String info = bufIn.readLine(); System.out.println("info:"+info); if(info.contains("欢迎")) break; } bufr.close(); s.close(); } } class UserThread implements Runnable { private Socket s; UserThread(Socket s) { this.s = s; } public void run() { String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+"....connected"); try { for(int x=0; x<3; x++) { BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); String name = bufIn.readLine(); if(name==null) //这里判断空,是因为如果对方尝试登录1次时候 强行结束,跳出for循环,都close(),就会发送-1过来,readLine()就会读null break; BufferedReader bufr = new BufferedReader(new FileReader("user.txt")); PrintWriter out = new PrintWriter(s.getOutputStream(),true); String line = null; boolean flag = false; while((line=bufr.readLine())!=null) { if(line.equals(name)) { flag = true; break; } } if(flag) { System.out.println(name+",已登录"); out.println(name+",欢迎光临"); break; } else { System.out.println(name+",尝试登录"); out.println(name+",用户名不存在"); } } s.close(); } catch (Exception e) { throw new RuntimeException(ip+"校验失败"); } } } class LoginServer { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10008); while(true) { Socket s = ss.accept(); new Thread(new UserThread(s)).start(); } } }
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * 简单架设java服务端,用ie访问,输入网址 http://127.0.0.1:10086 */ public class ServerDemo { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10086); Socket s = ss.accept(); System.out.println(s.getInetAddress().getHostAddress()+"...connect"); InputStream is = s.getInputStream(); byte[] buf = new byte[1024]; int len = is.read(buf); System.out.println(new String(buf,0,len)); //这里会把http协议打印出来 PrintWriter out = new PrintWriter(s.getOutputStream(),true); out.println("登录成功"); s.close(); ss.close(); } } GET / HTTP/1.1 Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */* Accept-Language: zh-CN User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E) Accept-Encoding: gzip, deflate Host: 127.0.0.1:10086 Connection: Keep-Alive ------------------------------------ 小知识 public class Demo { public static void main(String[] args) throws Exception{ //socket连接服务器写法一 Socket s1 = new Socket("127.0.0.1",30); //socket连接服务器写法二,两种功能一样,就写法有差别 Socket s2 = new Socket(); InetSocketAddress insa = new InetSocketAddress("127.0.0.1",80); s2.connect(insa); //public ServerSocket(int port,int backlog) backlog队列的最大长度。 就是同时在线人数 ServerSocket ss = new ServerSocket(10086, 10); } } -------------------------------------- 为什么要有域名?因为ip难记住,所以有了域名. 但是访问服务器要通过ip,所以域名要转成ip就要通过DNS服务器. 访问www.sina.com.cn ->电信DNS服务器->返回一个ip:188.188.188.188->然后再通过ip访问新浪服务器
端口扫描工具 import java.net.*; class ScanDemo { public static void main(String[] args) { for(int x=130; x<145; x++) { try { Socket s = new Socket("192.168.1.254",x); System.out.println(x+"...open"); } catch (Exception e) { System.out.println(x+"...closed"); } } } }
时间: 2024-10-10 13:47:30