📄 tcpserver.java
字号:
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPserver extends Thread{
Socket so;
FileInputStream from = null;
ByteArrayOutputStream baos = null;
byte[] b3 = new byte[500];
long x;
public TCPserver(Socket sso)
{
so = sso;
}
public void run()
{
System.out.println("Connection to TCPclient accepted: " + so);
try{
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(so.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(so.getInputStream()));
BufferedReader inbr =new BufferedReader(new InputStreamReader(in));
String filename = inbr.readLine();
if (filename == null) {
from.close();
so.close();
return;
}
File from_file = new File(filename);
try {
from = new FileInputStream(from_file);
}
catch (FileNotFoundException ex) {
out.writeByte(0); //通知client文件不存在
out.flush();
return;
}
byte [ ] rf = new byte[500];
try{
out.writeByte(1); //通知client文件传输紧接着开始
while(from.available()>0)
{
long len = from.read(rf);
if (len>0) {
out.write(rf, 0, (int) len);
}
}
out.flush();
}
catch (IOException e) {
System.out.println("Output error occured from sever!");
}
finally {
if (from != null)
try {
from.close();
}
catch(IOException e){;}
}
}
catch(IOException e){
}
try {
so.close();
}
catch (IOException ex1) {
}
}
public static void main(String[] args){
int port = 6666;
ServerSocket sso = null;
try{
try {
sso = new ServerSocket(port);
}
catch (IOException ex1) {
System.out.println("Can't bind to this port.");
}
while(true)
{
Socket so = sso.accept();
TCPserver tcps = new TCPserver(so);
System.out.println("Server has already been started");
tcps.start();
}
}
catch(IOException e){ ; }
finally{
try {
sso.close();
}
catch (IOException ex) { ; }
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -