文件发送:
发送端:
public class Send {
public static void main(String[] args) throws IOException {
//发送端
DatagramSocket send=new DatagramSocket();
//准备集装箱
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(new File("d:/Hello/timg.jpg")));
byte[] bs=new byte[1024];
int len;
InetAddress byName = InetAddress.getByName("127.0.0.1");
while ((len=bis.read(bs))!=-1){
DatagramPacket dp=new DatagramPacket(bs,len,byName,6666);
send.send(dp);
}
}
}
接收端:
public class Receive {
public static void main(String[] args) throws IOException {
DatagramSocket rec = new DatagramSocket(6666);
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("d:/Hello/timg1.jpg")));
int len;
do {
rec.receive(dp);
byte[] data = dp.getData();
len = dp.getLength();
bos.write(data, 0, len);
} while(len >= bytes.length);
bos.flush();
}
}
对话:
客户端:
public class ChartClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 8888);
System.out.println("连接中.....");
OutputStream os = socket.getOutputStream();
Scanner sca = new Scanner(System.in);
ReadThread th=new ReadThread(socket);
Thread thread=new Thread(th,"服务器端说");
thread.start();
while (true) {
System.out.println("你想说:");
String ss = sca.nextLine();
os.write(ss.getBytes());
os.flush();
}
}
}
服务端:
public class ChartServer {
static OutputStream os=null;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(8888);
System.out.println("等待连接中.....");
Socket server = serverSocket.accept();
System.out.println("成功连接!");
OutputStream os = server.getOutputStream();
ReadThread th=new ReadThread(server);
Thread thread=new Thread(th,"客户端说");
thread.start();
Scanner sca=new Scanner(System.in);
while(true){
System.out.println("你想说:");
String ss=sca.nextLine();
os.write(ss.getBytes());
os.flush();
}
}
}
创建线程达到不断接受消息的目的:
public class ReadThread implements Runnable {
private Socket socket;
private InputStream is;
public ReadThread(Socket socket) {
this.socket = socket;
try {
is=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
byte[] by=new byte[1024];
int len;
while(true){
try {
while (((len=is.read(by))!=-1)) {
System.out.println(Thread.currentThread().getName()+":"+new String(by,0,len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}