import java.io.*;
import java.net.*;
class IoTextDemo
{
public static void main(String[] args)throws Exception
{
//1.建立socket端点
Socket s = new Socket("192.168.126.1",10006);
//源
FileInputStream fis = new FileInputStream("C:\\daxiong.jpeg");
//目的
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1)
{
out.write(buf,0,len);
}
//告诉服务端数据已写完,否则一直卡在read那里
s.shutdownOutput();
InputStream in = s.getInputStream();
byte[] bufin = new byte[1024];
int num = in.read(bufin);
System.out.println(new String(bufin , 0 , num));
// BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));
// String str = bufin.readLine(); //读socket流,因为服务端卡在while那,所以不会发数据给客户端,所以一直卡在这,两边都卡着
// System.out.println(str);
fis.close();
s.close();
}
}
import java.io.*;
import java.net.*;
class InetRece
{
public static void main(String[] args)throws Exception
{
//1。建立ServerSocket服务
ServerSocket ss = new ServerSocket(10006);
//2.获取对象
//获取对象
Socket s = ss.accept();
String ip =s.getInetAddress().getHostAddress();
System.out.println(ip+"...connected");
InputStream in = s.getInputStream();
FileOutputStream fos = new FileOutputStream("E:\\hebing\\server7.jpeg");
//打印连接上的客户端
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());
//写 欢迎使用
//BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//bufout.write("上传成功");
//bufout.flush(); //如果这里不写数据根本就没写进socket输出流中,导致对面一直在等
fos.close();
s.close();
ss.close();
}
}
这是TCP上传一张图片,我这边很怪异的错,今天使用端口10006就没问题(昨天试了也不行),其他端口不行,麻烦各位有空帮我试试你们电脑上其他端口行不行,PS:记得不要用我的本地IP地址!!!
|
|