📄 starttcp.java
字号:
package javanet;
import java.net.*;
import java.io.*;
import java.util.Vector;
import javax.swing.*;
import java.awt.FileDialog;
public class startTCP extends JFrame implements Runnable{
Vector tasks=new Vector();
ServerSocket server;
Socket socket;
Vector list=new Vector();
FileDialog file=new FileDialog(this,"请选择保存路径");
PrintWriter pw;
DataOutputStream dos;
DataInputStream dis;
mainFrame frame;
String filename="";
String savepath;
int ans;
Object sels[]={"是","否"};
JOptionPane prompt=new JOptionPane();
DataOutputStream doos;
BufferedReader in;
public startTCP(mainFrame frame) throws IOException
{
server = new ServerSocket(8000);
this.frame=frame;
}
public void run()
{
boolean flag = true;
while (flag)
{
try
{
socket = server.accept();
list.add(socket.getInetAddress().toString());
tasks.add(socket);
dis = new DataInputStream(socket.getInputStream());
pw = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw.print("收到\n");
pw.flush();
filename=in.readLine();
ans=userConfirm(socket.getInetAddress().toString(),filename);
if(!(ans==0))
{
pw.close();
socket.close();
try {
throw new Exception();
}
catch (Exception ex1) {}
}
pw.print(ans);
pw.flush();//tell client the users choice
in.read();
pw.print(0);
pw.flush();
long size=Long.parseLong(in.readLine()); //////////
file.setFile(filename);
file.show();
savepath=file.getDirectory()+file.getFile();
//////////////////getFile
getFile(size,savepath);
}
catch (IOException ex) {}
}
}
public void getFile(long size,String path) throws IOException
{
doos=new DataOutputStream(socket.getOutputStream());
dis=new DataInputStream(socket.getInputStream());
dos=new DataOutputStream(new FileOutputStream(path));
int bit;
for(int i=0;i<size;i++)
{
doos.write(0);
doos.flush();
bit=dis.read();
dos.write(bit);
dos.flush();
}
pw.print(true);
pw.flush();
in.ready();
pw.close();
doos.close();
dis.close();
dos.close();
socket.close();
prompt.showMessageDialog(this,"文件接收成功!","提示",2);
}
public Vector linklist()
{
return list;
}
public void stopServer()
{
Socket s=null;
for(int i=0;i<tasks.size();i++)
{
s=(Socket)tasks.elementAt(i);
try {
s.close();
}
catch (IOException ex) {ex.printStackTrace();}
}
}
public int userConfirm(String ip,String filename)
{
int ans=prompt.showConfirmDialog(null,ip+"请求向你发送文件:"+filename+",是否同意?","请求",0,3,null);
return ans;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -