本帖最后由 谢洋 于 2013-3-12 14:04 编辑
import java.io.*;
import java.net.*;
class MyIE
{
public static void main(String[] args) throws Exception
{
//("192.168.1.101",8080)表示客户要连接到IP为:192.168.1.101的主机,并且连接到该主机上被8080的端口所标识的服务程序;
//端口可以这样理解:端口是用标记机主上的某个网络服务程序,,所以服务端要能接收客户的连接,那就它绑定端口要与客户端发往那个端口一致
Socket s = new Socket("192.168.1.101",8080);//这里的端口号不确定,不知道是不是8080
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
out.println("GET D:/JAVA/网编/TCP/myIE.html HTTP/1.1");
out.println("Accept:*/*");
out.println("Accept-Language: zh-cn");
out.println("Host: 192.168.1.101:10003");
out.println("Connection: Keep-Alive");
out.println();
out.println();
BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while((line=bufr.readLine())!=null)
{
System.out.println(line);
}
s.close();
}
}
import java.io.*;
import java.net.*;
class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10003);//我是服器,只收接连接到10003端口的客户
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
InputStream in = s.getInputStream();
byte[] b = new byte[1024];
int len = in.read(b);
System.out.println(new String(b,0,len));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
//out.println("客户端你好");
out.println("<font color='red' size='7'>客户端你好</font>");
s.close();
ss.close();
}
}
作一个比如吧:
如我们主机上开了两个网络程:QQ(假设端口1234) 和YY(5678)
当别人要把数据发给QQ或YY时,别人只发信息到你到主机上,那谁收好呢?这时就只好给这两程序各做一个不同的标识
然后别人把把要发往那个程序的数据就加上对应程序的标识(端口)
/*
192.168.1.101
GET / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shock
wave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application
/msword,
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 7
18; .NET CLR 2.0.50727)
Host: 192.168.1.101:10003
Connection: Keep-Alive
*/
|