?? 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("發(fā)送");
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(;;) //無限循環(huán) 接受數(shù)據(jù)并顯示
{
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
{ //發(fā)送數(shù)據(jù)
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
{ //發(fā)送文件數(shù)據(jù)
server_file= new ServerSocket (SERVICE_FILE);
socket_file= server_file.accept();
t1.append("文件發(fā)送開始"+(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("這是一個信息發(fā)送和接收的例子_client");
String hostname = args[0];
w1.datadis(hostname);
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -