简单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", ); // 为了发送数据,应该获取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(); // 通过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[];
int len = in.read(buf); System.out.println(new String(buf, , 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", ); // 定义读取键盘数据的流对象。
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(); 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", ); 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(); 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", );
FileInputStream fis = new FileInputStream("c:\\1.bmp");
OutputStream out = s.getOutputStream();
byte[] buf = new byte[];
int len = ;
while ((len = fis.read(buf)) != -) {
out.write(buf, , len);
} // 告诉服务端数据已写完
s.shutdownOutput();
InputStream in = s.getInputStream();
byte[] bufIn = new byte[];
int num = in.read(bufIn);
System.out.println(new String(bufIn, , num));
fis.close();
s.close();
}
} /*
* 服务端
*/
class PicServer {
public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket();
Socket s = ss.accept();
InputStream in = s.getInputStream();
FileOutputStream fos = new FileOutputStream("server.bmp");
byte[] buf = new byte[];
int len = ; while ((len = in.read(buf)) != -) {
fos.write(buf, , 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 != ) {
System.out.println("请选择一个jpg格式的图片");
return;
} File file = new File(args[]);
if (!(file.exists() && file.isFile())) {
System.out.println("该文件有问题,要么补存在,要么不是文件");
return;
} if (!file.getName().endsWith(".jpg")) {
System.out.println("图片格式错误,请重新选择");
return;
} if (file.length() > * * ) {
System.out.println("文件过大,没安好心");
return;
} Socket s = new Socket("192.168.1.254", );
FileInputStream fis = new FileInputStream(file);
OutputStream out = s.getOutputStream();
byte[] buf = new byte[]; int len = ; while ((len = fis.read(buf)) != -) {
out.write(buf, , len);
} // 告诉服务端数据已写完
s.shutdownOutput();
InputStream in = s.getInputStream();
byte[] bufIn = new byte[]; int num = in.read(bufIn);
System.out.println(new String(bufIn, , 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 = ;
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[]; int len = ;
while ((len = in.read(buf)) != -) {
fos.write(buf, , 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(); 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",); 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",); 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=; x<; 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=; x<; 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(); 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();
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostAddress()+"...connect"); InputStream is = s.getInputStream(); byte[] buf = new byte[]; int len = is.read(buf); System.out.println(new String(buf,,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=; x<; x++)
{
try
{
Socket s = new Socket("192.168.1.254",x); System.out.println(x+"...open"); }
catch (Exception e)
{
System.out.println(x+"...closed");
}
}
}
}

java网络之tcp的更多相关文章

  1. java 网络编程-tcp/udp

    --转自:http://blog.csdn.net/nyzhl/article/details/1705039 直接把代码写在这里,解释看这里吧:http://blog.csdn.net/nyzhl/ ...

  2. Java网络编程(TCP客户端)

    TCP传输:两个端点建立连接后会有一个传输数据的通道,这个通道就称为流,而且是建立在网络基础上的流,之为socket流,该流中既可以读取也可以写入. TCP的两个端点:一个客户端:ServerSock ...

  3. JAVA网络编程TCP通信

    Socket简介: Socket称为"套接字",描述IP地址和端口.在Internet上的主机一般运行多个服务软件,同时提供几种服务,每种服务都打开一个Socket,并绑定在一个端 ...

  4. java网络编程(TCP详解)

    网络编程详解-TCP 一,TCP协议的特点              面向连接的协议(有发送端就一定要有接收端)    通过三次连接握手建立连接 通过四次握手断开连接 基于IO流传输数据 传输数据大小 ...

  5. Java分享笔记:Java网络编程--TCP程序设计

    [1] TCP编程的主要步骤 客户端(client): 1.创建Socket对象,构造方法的形参列表中需要InetAddress类对象和int型值,用来指明对方的IP地址和端口号. 2.通过Socke ...

  6. java网络编程—TCP(1)

    演示tcp的传输的客户端和服务端的互访. 需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息. 客户端: 1,建立socket服务.指定要连接主机和端口. 2,获取socket流中的输出流. ...

  7. Java网络编程(TCP服务端)

    /* * TCP服务端: * 1.创建服务端socket服务,并监听一个端口 * 2.服务端为了给客户端提供服务,获取客户端的内容,可以通过accept方法获取连接过来的客户端对象 * 3.可以通过获 ...

  8. JAVA网络编程-----TCP沟通

    java采纳TCP变速箱使用Socket和ServerSocket数据传输. 采纳tcp步模式数据传输: 1.设定client和服务器 ,分别对应Socket和ServerSocket 2.建立连接后 ...

  9. Java网络编程のTCP/IP

    TCP/IP参考模型和TCP/IP协议 与OSI参考模型相似,TCP/IP参考模型汲取了网络分层的思想,而且对网络的层次做了简化,并在网络各层都提供了完善的协议,这些协议构成了TCP/IP协议集,简称 ...

随机推荐

  1. GitHub上有很多不错的iOS开源项目

    GitHub上有很多不错的iOS开源项目,个人认为不错的,有这么几个:1. ReactiveCocoa:ReactiveCocoa/ReactiveCocoa · GitHub:GitHub自家的函数 ...

  2. 学习笔记——迭代器模式Iterator

    迭代器模式,使用很多,但是很少实现.常用的集合都支持迭代器. 集合中的CreateIterator()可用于创建自己的迭代器,在里面通过调用迭代器的构造函数Iterator(Aggregate)来绑定 ...

  3. CentOS挂载硬盘

    1.查看当前硬盘使用状况: [root@gluster_node1 ~]# df -h 文件系统     容量 已用 可用 已用%% 挂载点 /dev/sda3 14G 2.4G 11G 19% / ...

  4. MFC中获取系统当前时间

    1.使用CTime类 CString str; //获取系统时间 CTime tm; tm=CTime::GetCurrentTime(); str=tm.Format("现在时间是%Y年% ...

  5. OutputDebugString输出调试信息到debugtrack

    OutPutDebugString()函数的输出则可以用DebugView捕获(DebugView也可以捕获TRACE宏的输出)eg: OutPutDebugString("输出第一调试信息 ...

  6. jQuery的dataTables插件实现中文排序

    最近在写Java web. 写JSP的时候发现一个很好玩的插件dataTables.分页.过滤.排序等等手到擒来. 哎哎哎,有点点可惜的是排序这个功能不支持中文.于是网上查查找找,现在把方法整理一下, ...

  7. nefu 899这也是裸的找

    #include <iostream> #include <algorithm> #include <cstdio> using namespace std; in ...

  8. [tableView dequeueReusableCellWithIdentifier:CellIdentifier] 后面forIndexPath:indexPath参数的解释

    解决以下错误: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'u ...

  9. 贾扬清分享_深度学习框架caffe

    Caffe是一个清晰而高效的深度学习框架,其作者是博士毕业于UC Berkeley的 贾扬清,目前在Google工作.本文是根据机器学习研究会组织的online分享的交流内容,简单的整理了一下. 目录 ...

  10. 图片应该放在drawable-hdpi下不要放在drawable下

    图片应该放在drawable-hdpi下或者mipmap-hdpi 不要放在drawable下,要不然显示有些不同