码迷,mamicode.com
首页 > 其他好文 > 详细

网络编程

时间:2015-01-30 16:06:54      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:网络编程      

其实,关于网络编程有着特有的格式,两个程序,一个服务器端,一个客户端,运行时先运行服务器端,在运行客户端,首先看下面两个小例子:

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

public class TCPServer {
	public static void main(String[] args) throws Exception {
	ServerSocket ss = new ServerSocket(6666);
	while(true){
		Socket s = ss.accept();
		System.out.println("A Client connection!");	
		DataInputStream dis = new DataInputStream(s.getInputStream());
		System.out.println(dis.readUTF());
		dis.close();
		s.close();
		}
	}	
}
这是服务器端的程序,格式很简单,首先新建一个服务器端口,用于接受客户端的信息,然后建立一个类似接口巡查的东西,时刻检查有没有信息传进来,就是

Socket s = ss.accept();

一旦接收到,就进行下一步,为了显示客户端传送过来的信息,必须用到流的内容,因此就有了这条语句,

DataInputStream dis = new DataInputStream(s.getInputStream());
这是流的标准语句,紧接着打印接受到信息,最后关闭。

下面看一下客户端的代码:

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

public class TCPClient {
	public static void main(String[] args) throws Exception{
		Socket s = new Socket("127.0.0.1",6666);	
		OutputStream ots = s.getOutputStream();
		DataOutputStream dos = new DataOutputStream(ots);
		Thread.sleep(30000);
		dos.writeUTF("HELLO");
		dos.flush();
		dos.close();
		s.close();
		
	}	
}
客户端其实和服务器端是一一对应的,Socket s = new Socket("127.0.0.1",6666);用来制定发信息的端口,

OutputStream ots = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(ots);

这两条语句就相当于:DataOutputStream dos = new DataOutputStream(s.getOutputStream());

然后传送数据:dos.writeUTF("HELLO");
最后关闭。


以上两个程序就是TCP最简单的发送信息的格式。


网络编程

标签:网络编程      

原文地址:http://blog.csdn.net/erpng/article/details/43305201

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