本文介绍了通过在java中的ArrayList TCP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在Java中通过TCP发送一个ArrayList?
我需要发送的整数的ArrayList,从客户端到服务器,反之亦然。
Thanxx
解决方案
进口java.io. *;
进口java.net *。
进口的java.util。*;
导入的java.util.concurrent *。公共类SerializeOverSocket { 私有静态ExecutorService的ExecutorService的=
Executors.newSingleThreadExecutor(); 公共静态无效的主要(字串[] args)抛出异常{
//启动服务器监听客户端
executorService.submit(新服务器());
视频下载(100);
//从客户端发送一个ArrayList
ArrayList的<整数GT;整数=
新的ArrayList<整数GT;(Arrays.asList(1,2,3,4,5));
插座S =新的Socket();
s.connect(新的InetSocketAddress(本地主机,1234));
ObjectOutputStream的出=新的ObjectOutputStream(s.getOutputStream());
out.writeObject(整数);
S.CLOSE();
} 静态类服务器实现Runnable {
公共无效的run(){
尝试{
ServerSocket的服务器=新的ServerSocket(1234);
插座ClientSocket的= server.accept();
ObjectInputStream中的=
新的ObjectInputStream(clientSocket.getInputStream());
对象o = in.readObject();
的System.out.println(接收服务器上的这个对象:+ O);
clientSocket.close();
server.close();
executorService.shutdown();
}赶上(IOException异常五){
// TODO:收件箱
抛出新UnsupportedOperationException异常(不写);
}赶上(ClassNotFoundException的E){
// TODO:收件箱
抛出新UnsupportedOperationException异常(不写);
}
}
}
}
How can I send an arraylist through tcp in Java?I need to send an arraylist of integers, from client to server and vice verse.
Thanxx
解决方案
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
public class SerializeOverSocket {
private static ExecutorService executorService =
Executors.newSingleThreadExecutor();
public static void main(String[] args) throws Exception {
// Start a server to listen for a client
executorService.submit(new Server());
Thread.sleep(100);
// Send an ArrayList from a client
ArrayList<Integer> integers =
new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
Socket s = new Socket();
s.connect(new InetSocketAddress("localhost", 1234));
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
out.writeObject(integers);
s.close();
}
static class Server implements Runnable {
public void run() {
try {
ServerSocket server = new ServerSocket(1234);
Socket clientSocket = server.accept();
ObjectInputStream in =
new ObjectInputStream(clientSocket.getInputStream());
Object o = in.readObject();
System.out.println("Received this object on the server: " + o);
clientSocket.close();
server.close();
executorService.shutdown();
} catch (IOException e) {
// TODO: Write me
throw new UnsupportedOperationException("Not written");
} catch (ClassNotFoundException e) {
// TODO: Write me
throw new UnsupportedOperationException("Not written");
}
}
}
}
这篇关于通过在java中的ArrayList TCP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!