码迷,mamicode.com
首页 > 编程语言 > 详细

java网络编程

时间:2015-09-05 01:20:58      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:网络编程   项目开发   网络通讯   聊天室   发送信息   

    最近因为项目开发有设计到网络通讯功能,而我对于这块来说也是一块雾区,于是就上网查了些资料,经过几天的学习与开发终结了一点点。

    

网络编程

核心

TCP、UDP

TCP协议

服务器/客户端协议,适合做聊天室工具服务端和客户端是互通的也就是服务端可以成为客户端收消息客户端也可

以像服务端一样发送消息具体操作还请看代码。

UDP协议

广播协议,是一种不可靠的协议,服务器可以向多个用户发送信息,用户也可以向服务器或其它用户发送消息,

服务器可以是客户端,客户端也可以是服务器,支持批量发送,具体实现还请看代码。

核心类

TCP

1.ServerSocket 服务器套接字

2.Socket 客户端套接字

3.BufferedReader 缓冲字符输入流

4.PrintWriter 文本输出流打印对象

UDP

1.DatagramSocket 发送和接收数据报包的套接字

2.DatagramPacket 数据报包

3.BufferedReader 缓冲字符输入流


废话不多说直接上代码

Tcpclient.java

import java.net.*;

import java.io.*;

public class Tcpclient {


/**

* @param args

* @throws IOException 

* @throws UnknownHostException 

*/

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

while(true){

//声明服务器

ServerSocket server = new ServerSocket(8855);

Thread t = new Thread(new Talk1());

t.start();

//声明客户端

Socket client = null;

client = server.accept();

BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));

String str = reader.readLine();

reader.close();

if(!"".equals(str)&&null!=str){

System.out.println("收到由"+client.getLocalAddress().getAddress()+"发送过来的消息:");

System.out.println(str);

client.close();

server.close();

}

try {

client = new Socket(InetAddress.getByName("localhost"),8885);

//向客户端打印信息

PrintWriter print = null;

//准备向客户端打印信息

print = new PrintWriter(client.getOutputStream());

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

System.out.println("请输入发送内容:");

String st = readerin.readLine();

print.println(st);

print.close();

client.close();

} catch (Exception e) {

System.out.println("您的好友没在线");

}

}

}

}

class Talk1 implements Runnable{


@Override

public void run() {

try {

Socket client = null;

client = new Socket(InetAddress.getByName("localhost"),8885);

//向客户端打印信息

PrintWriter print = null;

//准备向客户端打印信息

print = new PrintWriter(client.getOutputStream());

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

System.out.println("请输入发送内容:");

String st = readerin.readLine();

print.println(st);

print.close();

client.close();

} catch (Exception e) {

System.out.println("您的好友没在线");

}

}

}


TcpServer.java

import java.io.*;

import java.net.*;


public class TcpServer {


/**

* @param args

* @throws IOException 

*/

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

while(true){

//声明服务器

ServerSocket server = new ServerSocket(8885);

Thread t = new Thread(new Talk());

t.start();

//声明客户端

Socket client = null;

client = server.accept();

BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));

String str = reader.readLine();

reader.close();

if(!"".equals(str)&&null!=str){

System.out.println("收到由"+client.getLocalAddress().getAddress()+"发送过来的消息:");

System.out.println(str);

client.close();

server.close();

}

}

}


}


class Talk implements Runnable{


@Override

public void run() {

try {

Socket client = null;

client = new Socket(InetAddress.getByName("localhost"),8855);

//向客户端打印信息

PrintWriter print = null;

//准备向客户端打印信息

print = new PrintWriter(client.getOutputStream());

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

System.out.println("请输入发送内容:");

String st = readerin.readLine();

print.println(st);

print.close();

client.close();

} catch (Exception e) {

System.out.println("您的好友没在线");

}

}

}


其实,聊天室没有服务端和客户端之分

UDPClient.java

import java.net.*;

import java.io.*;


public class UDPClient {


/**

* @param args

*/

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

Thread t1 = new Thread(new MonitorMsg());

t1.start();//启动服务器

//本地socket

DatagramSocket datagramSocket = new DatagramSocket(3979);

String msg="";

System.out.println("请输入发送信息:");

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

msg = reader.readLine();

DatagramPacket packsend = new DatagramPacket(msg.getBytes(),0, msg.getBytes().length,InetAddress.getByName("localhost"), 4979);

datagramSocket.send(packsend);

//用于存放从服务端发送过来的消息

byte[] b = new byte[1024];

DatagramPacket pack = new DatagramPacket(b,b.length);

datagramSocket.receive(pack);

String str = new String(pack.getData(),0,pack.getLength());

if(!"".equals(str)&&null!=str){

System.out.println("接收到由服务端传回的消息:");

}

//System.out.println("c_len:"+pack.getLength());

System.out.println(str);

datagramSocket.close();

}


}


UDPServer.java     

import java.net.*;

import java.io.*;


public class UDPServer {


/**

* @param args

*/

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

Content.moni_num=1;//设置我已经启动了

//声明服务端套件字

DatagramSocket datagramSocket = null;

//声明数据报包

DatagramPacket pack = null;

datagramSocket = new DatagramSocket(4979);

byte[] b = new byte[1024];

pack = new DatagramPacket(b, 0, b.length);

datagramSocket.receive(pack);

if(pack.getData().length>0){

System.out.println("收到客户"+pack.getAddress()+"的消息!");

System.out.println(new String(pack.getData(),0,pack.getLength()));

}

String str = "Hello UDP";

//动态发送内容

System.out.println("请输入发送给客户端的内容:");

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

str = bur.readLine();

//System.out.println("b_len:"+str.getBytes().length+"  s_len:"+str.length());

pack = new DatagramPacket(str.getBytes(),0,str.getBytes().length,InetAddress.getByName("localhost"),3979);

datagramSocket.send(pack);

datagramSocket.close();

}

}


MonitorMsg.java


/**

 * 查看服务端是否启动

 * @author Administrator

 *

 */

public class MonitorMsg implements Runnable{

@Override

public void run() {

if(Content.moni_num==0){

UDPServer udpser = new UDPServer();

String[] st = {};

try {

//启动服务端

Content.moni_num=1;

udpser.main(st);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


}


Content.java

/**

 * 监听控制对象

 * @author Administrator

 *

 */

public class Content {

public static int moni_num=0;//

//public static int moni_num1=0;

}


代码有点长,能坚持看到这鼓励下

java网络编程

标签:网络编程   项目开发   网络通讯   聊天室   发送信息   

原文地址:http://haj1cto.blog.51cto.com/8983322/1691437

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!