初学JAVA网络编程示例
服务端
package com.xuedao.main;
//服务端
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Sever {
public static void main(String[] args) {
try {
//端口,相当于服务在计算机上面的位置,最好取1000-63000多
ServerSocket sever = new ServerSocket(9999);
while(true) {
//程序会阻塞在这,直到客户端连接
Socket cli = sever.accept();
Thread t = new Thread(new SeverRunner(cli));
t.start();
// //获取客户端的输出流
// OutputStream out = cli.getOutputStream();
// out.write("你好".getBytes());
// //等待客户的回应,获取客户端的输入流
// InputStream in = cli.getInputStream();
// byte[] b = new byte[1024];
// int l = in.read(b);
//
// System.out.println("客户端说:"+new String(b,0,l));
// //sever.close();关闭,停止服务
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
创建一个线程来处理服务
package com.xuedao.main;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
//做:和客户对话
public class SeverRunner implements Runnable{
private Socket cli;
public SeverRunner(Socket cli) {
super();
this.cli = cli;
}
@Override
public void run() {
//获取客户端的输出流
OutputStream out;
try {
//获取客户端的输出流 给客户说话
out = cli.getOutputStream();
out.write("你好".getBytes());
//等待客户的回应,获取客户端的输入流
InputStream in = cli.getInputStream();
byte[] b = new byte[1024];
int l = in.read(b);
Thread.sleep(10000);
System.out.println("客户端说:"+new String(b,0,l));
//sever.close();关闭,停止服务
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端
package com.xuedao.main;
//客户端
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
//创建即是连接到服务端的过程 ( ipv4地址 ,端口号)
Socket cli = new Socket("192.168.22.160", 9999);
InputStream in = cli.getInputStream();
byte[] b = new byte[1024];
int l = in.read(b);
System.out.println("服务端说:"+new String(b,0,l));
OutputStream out = cli.getOutputStream();
out.write("不好,再见".getBytes());
cli.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}