eg: – > 客户端发送一个文件给服务端,服务端将文件保存在本地
首先这里我们先给出服务器端
package 网络编程.TCP网络编程;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class Server2 {
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket(9090);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("hi.png"));
byte [] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!= -1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
socket.close();
ss.close();
}
}
其次这里我们给出客户端
package 网络编程.TCP网络编程;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client2 {
//注意: 实际编程中我们应该是使用try --- catch --- finally将异常处理掉,但是这里我们为了思路的清晰使用了throws + 异常对象将异常抛出了
public static void main(String[] args) throws IOException{
//创建Socket对象,Socket对象作为网络传输的节点,我们要给客户端的Socket中封装有目标的IP地址+端口号
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("abc.png"));
byte [] bytes = new byte[1024];
int len = 0;
while((len = fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
os.close();
fis.close();
socket.close();
}
}
注意:我们先启动服务端之后再启动客户端
如果我们先启动了客户端,这个时候会抛出一个运行时异常:java.net.ConnectException
因为这个时候我们是TCP协议下的网络编程 ---- 这个时候我们要进行网络传输必须要保证服务端是在线的 补充: IO流资源和Socket资源,还有数据库连接等都物理连接都是要我们去手动关闭的
JVM不能回收这些物理连接
所以我们一般要将关闭这些物理资源的操作放到finally代码块中 补充2:
创建Socket对象和创建ServerSocket对象都是会抛出 : java.io.IOException


![TCP网络编程 [Java] TCP网络编程 [Java]](http://www.mshxw.com/aiimages/31/705159.png)
