我写的代码
package org.com.internet;
import java.io.*;
import java.net.*;
//客户端
public class Tcp1 {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
//创建客户端对象
Socket s=new Socket("192.168.1.102",10007);
//读取客户端已有的图片
File f=new File("c:\\1.jpg");
FileInputStream fs=new FileInputStream(f);
//将客户端的数据输出到服务器端
OutputStream out=s.getOutputStream();
byte[] b=new byte[1024];
int len=0;
while((len=fs.read(b))!=-1){
out.write(b, 0, len);
}
//数据读取完毕
s.shutdownOutput();
//读取数据
InputStream in=s.getInputStream();
byte[] b1=new byte[1024];
int len1=in.read(b1);
System.out.println(new String(b1,0,len1));
//关闭流
fs.close();
s.close();
}
}
//服务端
class TcpServer{
public static void main(String args[]) throws Exception{
//创建服务器端对象
ServerSocket ss=new ServerSocket(10007);
//服务器端接收客户端发送的数据
Socket s=ss.accept();
//获取输入流
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip);
InputStream in=s.getInputStream();
//创建上传对象路径
File f=new File("D.jpg");
FileOutputStream fos=new FileOutputStream(f);
//读取输入流
byte[] b2=new byte[1024];
int len=0;
while((len=in.read(b2))!=-1){
fos.write(b2, 0, len);
}
//输出数据到客户端去
OutputStream out=s.getOutputStream();
out.write("上传成功".getBytes());
//关闭流
fos.close();
ss.close();
}
}
出现问题:
先用eclipse运行 Tcp1时,出现如下异常
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at org.com.internet.Tcp1.main(Tcp1.java:13)
运行TcpServer,在运行tcp1时,出现如下异常:
192.168.1.102
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at org.com.internet.TcpServer.main(Tcp1.java:65)
|