java中传输数据一般有两种协议:一是TCP协议 还有一个是UDP协议,对于两种协议区别,大家问百度吧。下面举例说明TCP协议应用。本例只是做一个简单的实例,程序些的并不健壮。
服务器端:
import java.io.IOException;
import java.net.*;
import java.io.*;
public class NetTest implements Runnable{
/**
* @param args
*/
ServerSocket ss;
public static void main(String[] args) {
// TODO Auto-generated method stub
NetTest nt=new NetTest();
Thread t=new Thread(nt);
t.start();
}
public NetTest()
{
try {
ss=new ServerSocket(9999);//创建ServerSocket服务并制定监听端口
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//利用线程不停的进行监听
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
System.out.println("服务端在9999端口监听");
Socket s=ss.accept();//服务端在9999端口监听
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));//得到网络输入流
String info=br.readLine();//读取数据
System.out.println("服务器接收到 "+info);
// PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
// pw.println("客服端,您好,你发的信息我已收到!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
客户端:
import java.io.IOException;
import java.net.*;
import java.io.*;
public class NetTestClient implements Runnable{
/**
* @param args
*/
Socket s;
public static void main(String[] args) {
// TODO Auto-generated method stub
NetTestClient ntc=new NetTestClient();
}
public NetTestClient()
{
try {
s=new Socket("127.0.0.1",9999);// 创建到服务器的连接
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);//获取网络输出流
pw.println("你好,我是客服端1号");
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));//获取网络输入流
System.out.println(" 我收到服务器回发信息"+br.readLine());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
s.close();//关闭网络
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void run() {
// TODO Auto-generated method stub
}
}
|
|