网络编程
想要进行网络编程,我们首先要找到要进行通讯的主机,那么如何找到主机呢,就需要ip和端口号,每个主机都有对应的ip地址,找到了ip地址就找到了相应的主机,再在主机上找到对应端口号的程序,通讯就能进行。
-
实现网络通讯,至少需要两个个体,而在我们的程序中,称呼这两个个体为服务器端和客户端。下面用代码来演示:
-
实现的效果:要写一个界面,在客户端发送,服务器端接收
//客户端
public class DrawClient {
public void showUI() {
//界面
JFrame jf = new JFrame();
jf.setSize(400,300);
jf.setTitle("客户端 Meetting by gzh4869--0.1");
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(3);
FlowLayout fl = new FlowLayout();
jf.setLayout(fl);
JButton jub = new JButton("发送");
jf.add(jub);
JTextField jtf = new JTextField(20);
jf.add(jtf);
jf.setVisible(true);
jub.addActionListener(new ActionListener() {
String s;
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
//建立一个客户端 ip 端口号
Socket st = new Socket("127.0.0.1",4578);
//输入输出流
InputStream ips = st.getInputStream();
OutputStream ops = st.getOutputStream();
//将文本框中的内容发送到服务器端
s = jtf.getText();
ops.write(s.getBytes());
//关闭流
ops.close();
}catch(Exception ef) {
ef.printStackTrace();
}
}
});
}
public static void main(String[] args) {
DrawClient dc = new DrawClient();
dc.showUI();
}
}
//服务器端
//先写一个方法判断是否连接成功,确定连接成功之后在接收从客户端发来的代码,并将其反映到文本框上
public class ConnServer {
InputStream ips;
OutputStream ops;
public boolean Conn() {
try {
ServerSocket sst = new ServerSocket(4578);
Socket st = sst.accept();
System.out.println("连接成功");
//输入输出流
ips = st.getInputStream();
ops = st.getOutputStream();
return true;
}catch(Exception ef) {
ef.printStackTrace();
}
return false;
}
}
public class DrawServer {
public void showUI() {
JFrame jf = new JFrame();
jf.setSize(400, 300);
jf.setTitle("服务器 Meetting by gzh4869--0.1");
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(3);
FlowLayout fl = new FlowLayout();
jf.setLayout(fl);
JTextArea jea = new JTextArea(10, 30);
jf.add(jea);
jf.setVisible(true);
ConnServer cs = new ConnServer();
if (cs.Conn()) {
try {
int len = 0;
byte[] buf = new byte[1024];
while ((len = cs.ips.read(buf)) != -1) {
}
String s1 = new String(buf);
jea.setText(s1);
System.out.println(new String(buf));
} catch (Exception ef) {
ef.printStackTrace();
}
}
}
public static void main(String[] arg) {
DrawServer ds = new DrawServer();
ds.showUI();
}
}
- 效果(在客户端输入文本,点击发送,给服务器)