📄 filerecieve.java
字号:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class win extends Frame implements ActionListener
{
TextArea t1;
TextField t2;
Button b1,b2;
String host;
Label l1;
PrintStream pout;
public static final int SERVICE_PORT = 13;
public static final int SERVICE_PORT2 =15;
public static final int SERVICE_FILE = 17;
ServerSocket server;
Socket nextClient,rec,rec_file;
BufferedReader reader;
win(String s)
{
//这段代码是显示界面
super(s);
setVisible(true);
setSize(400,500);
setLayout(new FlowLayout());
l1=new Label("聊天记录");
t1=new TextArea("",20,50);
t2=new TextField("",50);
b1=new Button("文件接收");
b2=new Button("发送");
add(l1);
add(t1);
add(b1);
add(t2);
add(b2);
l1.setVisible(true);
t1.setVisible(true);
t2.setVisible(true);
b1.setVisible(true);
b2.setVisible(true);
b2.addActionListener(this);
b1.addActionListener(this);
this.show();
try
{
server = new ServerSocket (SERVICE_PORT);
}
catch (Exception ioe)
{
System.err.println ("error :- " + ioe);
}
}
public void datadis(String hostname)
{
host=hostname;
for(;;) //无限循环 接受数据并显示
{
try
{
rec = new Socket (hostname, SERVICE_PORT2);
System.out.println ("Connection established,the local port is:"+rec.getLocalAddress()+rec.getLocalPort());
reader = new BufferedReader (new InputStreamReader(rec.getInputStream()));
t1.append(reader.readLine()+(char)13+(char)10);
}
catch (Exception ioe)
{
System.err.println (" wait server................... - " + ioe);
}
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==b2)
{
try
{ //发送数据
nextClient = server.accept();
OutputStream out = nextClient.getOutputStream();
pout = new PrintStream (out);
pout.print( t2.getText());
pout.flush();
nextClient.close();
}
catch (Exception ioe)
{
System.err.println ("error :- " + ioe);
}
}
if (e.getSource()==b1)
{
try
{ //接受文件数据
rec_file = new Socket (host, SERVICE_FILE);
t1.append("文件接收开始"+(char)13+(char)10);
BufferedInputStream input= new BufferedInputStream (rec_file.getInputStream());
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream ( "04_test.rm"));
int data;
System.out.println("recieve..............");
while ((data=input.read())!=-1)
{
output.write(data);
}
System.out.println("recieve ok");
output.close();
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
}
}
}
// Chapter 6, Listing 2
public class filerecieve
{
public static void main(String args[])
{
win w1=new win("这是一个信息发送和接收的例子_server");
String hostname = args[0];
w1.datadis(hostname);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -