java--Networking编程问题
发布网友
发布时间:2024-10-03 04:33
我来回答
共2个回答
热心网友
时间:2024-12-15 01:15
我这里只是简单地写了发送消息,然后接收,然后写入文件,GUI要的话要晚些给你
public class TextClient {
public static void main(String[] args) {
new TextClient();
}
public TextClient() {
send();
}
private void send() {
OutputStream outputStream = null;
try {
Socket socket = new Socket("localhost", 2012);
outputStream = socket.getOutputStream();
System.out.println("发送");
outputStream.write("要发送的消息".getBytes());
System.out.println("发送完毕");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
-------------------------------------------------------------------------------
public class TextServer {
public static void main(String[] args) {
new TextServer();
}
public TextServer() {
receive();
}
private void receive() {
FileOutputStream fileOutputStream = null;
InputStream inputStream = null;
try {
ServerSocket serverSocket = new ServerSocket(2012);
fileOutputStream = new FileOutputStream(new File("Receive.txt"));
Socket socket = serverSocket.accept();
inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int len = 0;
System.out.println("接收");
while ((len = inputStream.read(b)) > -1) {
fileOutputStream.write(b, 0, len);
}
System.out.println("接收完毕");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null)
fileOutputStream.close();
if (inputStream != null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
追问O(∩_∩)O谢谢,我在线等
追答
//刚刚下班,简单的弄了一下,不知道是不是你想要的
private JTextArea area;
public TextClient() {
//改一下这里
init();
}
//------加上这三个方法就有UI了
private void init(){
this.setTitle("TextClient");
this.setSize(new Dimension(350, 300));
this.setLocationRelativeTo(null);
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(3);
JScrollPane area = geTextArea();
getContentPane().add("Center", area);
getContentPane().add("South", getButton());
this.setVisible(true);
}
private JButton getButton() {
JButton button = new JButton("Send");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String message = area.getText().trim();
send(message);
System.exit(0);
}
});
return button;
}
private JScrollPane geTextArea() {
area = new JTextArea();
JScrollPane scrollPane = new JScrollPane(area);
scrollPane
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
return scrollPane;
}
//-----------------------
热心网友
时间:2024-12-15 01:15
不会,会也不给你说