📄 filesend.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;
Label l1;
public static final int SERVICE_PORT = 13;
public static final int SERVICE_PORT2 = 15;
public static final int SERVICE_FILE = 17;
Socket rec,nextClient,socket_file;
ServerSocket server,server_file;
BufferedReader reader;
PrintStream pout;
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);
b1.addActionListener(this);
b2.addActionListener(this);
//this.pack();
this.show();
try
{
server = new ServerSocket (SERVICE_PORT2);
}
catch (Exception ioe)
{
System.err.println("error :- " + ioe);
}
}
public void datadis(String hostname)
{
for(;;) //无限循环 接受数据并显示
{
try
{
rec = new Socket (hostname, SERVICE_PORT);
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........... ");
}
}
}
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
{ //发送文件数据
server_file= new ServerSocket (SERVICE_FILE);
socket_file= server_file.accept();
t1.append("文件发送开始"+(char)13+(char)10);
BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream ("04.rm"));
BufferedOutputStream out = new BufferedOutputStream(socket_file.getOutputStream());
try
{
int data = fileInput.read();
while (data != -1)//read()方法到达流末尾返回-1。
{
out.write(data);
data = fileInput.read();
}
fileInput.close();
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
socket_file.close();
System.out.println("send ok");
}
catch (Exception ioe)
{
System.err.println ("error :- " + ioe);
}
}
}
}
// Chapter 6, Listing 2
public class filesend
{
public static void main(String args[])
{
win w1=new win("这是一个信息发送和接收的例子_client");
String hostname = args[0];
w1.datadis(hostname);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -