国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

談?wù)凾CP和UDP的一些簡(jiǎn)單應(yīng)用

2019-11-17 06:13:36
字體:
供稿:網(wǎng)友
  網(wǎng)絡(luò)編程中最重要的就是SOCKET,它其實(shí)也就是監(jiān)聽端口的原理。和我們用手機(jī)發(fā)短信的原理應(yīng)該是大致無二(我是這樣理解的),而java最出色的一點(diǎn)也就是“無痛苦連網(wǎng)”。

  網(wǎng)絡(luò)最基本的精神就是讓兩臺(tái)機(jī)器連接起來,“被呼叫的一方”也就是服務(wù)器,而“找人的一方”則叫做客戶機(jī),所以說在連接中服務(wù)器、客戶機(jī)也就是一個(gè)相對(duì)的概念了。而我們對(duì)機(jī)器的標(biāo)識(shí)主要是通過ip地址和端口來區(qū)分的。

  “傳輸控制協(xié)議”TCP和“用戶數(shù)據(jù)報(bào)協(xié)議”是兩種不同的協(xié)議,JAVA對(duì)這兩種協(xié)議的支持基本是一致的,而它們本身最大的區(qū)別也就是發(fā)送的可靠性和速率,前者相比后者是可靠協(xié)議,后者當(dāng)然是速度快得多了,下面我們分別用兩個(gè)SOCKET下演示:

eg1:

//Clients.java

import java.io.*;
import java.net.*;


public class Clients
{
public static void main(String[] args) throws Exception
{
InetAddress addr = InetAddress.getByName(null);
Socket socket = new Socket(addr,2000);
PRintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
byte[] b = new byte[2048];
String msg = new String(b,0,System.in.read(b));
out.println(msg);
socket.close();
}
}


//Servers.java


import java.io.*;
import java.net.*;

public class Servers
{
public static void main(String[] args) throws Exception
{
ServerSocket s = new ServerSocket(2000);
try{
while(true){
Socket socket = s.accept();
try{
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
StringBuffer sb = new StringBuffer();
int c;
while( (c = in.read()) != -1 ){
char ch = (char)c;
sb.append(ch);
}
System.out.println(sb.toString());

}catch(IOException e){
socket.close();
}finally{
socket.close();
}
}//while
}finally{
s.close();
}//try
}//main
}


此程式主要用Servers來進(jìn)行無限監(jiān)聽,而Clients是客戶機(jī)發(fā)送程式,他們的端口全采用2000。


eg2:

//UDPsend.java
import java.io.*;
import java.net.*;

/**
* This class sends the specified text or file as a datagram to the
* specified port of the specified host.
**/
public class UDPSend {
public static final String usage =
"Usage: java UDPSend .../n" +
" or: java UDPSend -f ";

public static void main(String args[]) {
try {
// Check the number of arguments
if (args.length < 3)
throw new IllegalArgumentException("Wrong number of args");

// Parse the arguments
String host = args[0];
int port = Integer.parseInt(args[1]);

// Figure out the message to send.
// If the third argument is -f, then send the contents of the file
// specified as the fourth argument. Otherwise, concatenate the
// third and all remaining arguments and send that.
byte[] message;
if (args[2].equals("-f")) {
File f = new File(args[3]);
int len = (int)f.length(); // figure out how big the file is
message = new byte[len]; // create a buffer big enough


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宁安市| 新丰县| 承德市| 于田县| 泸溪县| 惠水县| 咸阳市| 大邑县| 奈曼旗| 泰兴市| 威海市| 泰来县| 怀安县| 双柏县| 临桂县| 涿州市| 安龙县| 金秀| 高台县| 开远市| 南通市| 上思县| 思茅市| 元朗区| 巴青县| 灵川县| 德兴市| 巢湖市| 安庆市| 怀远县| 于田县| 邵阳市| 文成县| 宣化县| 齐河县| 富锦市| 法库县| 彩票| 肃南| 肃南| 博爱县|