天天看点

TCP与UDP网络编程

一、TCP与UDP的区别:

**主要抓住是否服务端与客户端需要建立连接这一关键点。

1)TCP要求服务端与客户端之间要先建立连接才能进行通信,比如打电话。TCP工作与传输层,是可靠的协议。由于要先建立连接,故效率也相对较低,一般用于大数据量的传输。

2)UDP则是服务端与客户端之间不用先建立连接就能进行通信,比如qq、微信。只负责将信息发出,不管信息是否成功传出。因此是不可靠的传输协议。但由于无需事先建立连接,故传输速度较快,效率比较高。但是传输的数据量有限制,并且较为容易出现丢包现象。

二、TCP与UDP编程实例

--------------------用UDP协议实现一个聊天程序---------------------

利用的技术:多线程,接口

package haha;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

class Send implements Runnable

{

private DatagramSocket ds;

Send(DatagramSocket ds)

{

this.ds = ds;

}

@Override

public void run() {

// TODO Auto-generated method stub

BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

String line = null;

try {

while((line=bufr.readLine())!=null)

{

if("123".equals(line))

{

break;

}

byte[] buf = line.getBytes();

DatagramPacket dp =new DatagramPacket(buf, buf.length,InetAddress.getByName("172.27.33.8"),10003);

ds.send(dp);

}

} catch (IOException e) {

throw new RuntimeException("发送端出错!");

}

}

}

class Rece implements Runnable

{

private DatagramSocket ds;

Rece(DatagramSocket ds)

{

this.ds = ds;

}

@Override

public void run() {

// TODO Auto-generated method stub

while(true)

{

byte [] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, buf.length);

try {

ds.receive(dp);

String ip =dp.getAddress().getHostAddress();

String data = new String(dp.getData(),0,dp.getLength());

} catch (IOException e) {

throw new RuntimeException("接收端出错!");

}

}

}

}

public class ChatDemo

{

public static void main(String [] args) throws Exception

{

DatagramSocket sendSocket = new DatagramSocket();

DatagramSocket receSocket = new DatagramSocket(10003);

new Thread(new Send(sendSocket)).start();

new Thread(new Rece(receSocket)).start();

}

}

------------------------用TCP协议实现用户登录操作-----------------

需求://用户进行登录,最多登录三次

客户端代码:

public class UserLoginClientDemo {

public static void main(String[] args) throws UnknownHostException, Exception {

// TODO Auto-generated method stub

Socket s = new Socket("172.27.33.8", 10025);

BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

PrintWriter out = new PrintWriter(s.getOutputStream(),true);

BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));

for(int i=0 ; i<3 ; i++)

{

String line = bufr.readLine();

if(line==null)

break;

out.println(line);

String info = bufIn.readLine();

System.out.println("info:"+info);

if(info.contains("欢迎"))//一次登录成功

break;

}

bufr.close();

s.close();

}

}

服务端代码:

public class UserLoginServerDemo {

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

ServerSocket ss = new ServerSocket(10025);

while(true)

{

Socket s = ss.accept();

new Thread(new UserThread(s)).start();

}

}

}

class UserThread implements Runnable

{

private Socket s;

public UserThread(Socket s) {

this.s = s;

}

public void run() {

// TODO Auto-generated method stub

String ip = s.getInetAddress().getHostAddress();

System.out.println(ip+"......connected....");

try {

for(int i=0;i<3;i++)

{

BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));

String name = bufIn.readLine();

if(name==null)

{

break;

}

BufferedReader bufr = new BufferedReader(new FileReader("C:\\user.txt"));

PrintWriter out = new PrintWriter(s.getOutputStream(),true);

String line = null;

boolean falg = false;

while((line=bufr.readLine())!=null)

{

if(line.equals(name))

{

falg  = true;

break;

}

}

if(falg)

{

System.out.println(name+",已登录");

out.println(name+",欢迎光临!");

break;

}

else

{

System.out.println(name+"尝试登录");

out.println(name+"用户名不存在!");

}

}

s.close();//关闭客户端

} catch (IOException e) {

throw new RuntimeException(ip+"校验失败!");

}

}

}

三、总结

1)TCP程序执行时必须先启动服务端,客户端向服务端发出请求,只有先开启服务端,程序才不会报错

2)在服务端尽量设置时间限制,节省资源

3)在服务端得用多线程,这样能解决多个客户端登录一个服务端

继续阅读