程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java socket 入門編程實例

Java socket 入門編程實例

編輯:關於JAVA
這是一個C/S之間通信的例子,在JDK1.4下測試通過.
//服務器端源程序tcpserver.Java

import Java.io.*;
import Java.Net.*;
public class tcpserver 
{
public static void main(String[] args) throws IOException
{
ServerSocket svrsoc=null;
Socket soc=null;
DataInputStream in=null;
PrintStream out=null;
InetAddress clIEntIP=null;
String str=null;
try
{
svrsoc=new ServerSocket(8000);
System.out.println("Server start....");
soc=svrsoc.accept();

in=new DataInputStream(soc.getInputStream());
out=new PrintStream(soc.getOutputStream());
clIEntIP=soc.getInetAddress();
System.out.println("Client's IP address:"+clIEntIP);
out.println("welcome.....");
str=in.readLine();
while (!str.equals("quit"))
{
System.out.println("ClIEnt said:"+str);
str=in.readLine();
}
System.out.println("ClIEnt want to leave");
}
catch(Exception e)
{
System.out.println("error:"+e);
}
finally
{
in.close();
out.close();
soc.close();
svrsoc.close();
System.exit(0);
}
}
}

//客戶端源程序tcpclIEnt.Java

import Java.io.*;
import Java.Net.*;
public class tcpclIEnt 
{
public static void main(String[] args) throws IOException
{
Socket soc=null;
DataInputStream in=null;
PrintStream out=null;
DataInputStream sysin=null;
String strin=null;
String strout=null;
try
{
soc=new Socket(args[0],8000);
System.out.println("Connecting to the Server");
in=new DataInputStream(soc.getInputStream());
out=new PrintStream(soc.getOutputStream());
strin=in.readLine();
System.out.println("Server said:"+strin);
sysin=new DataInputStream(System.in);
strout=sysin.readLine();
while (!strout.equals("quit"))
{
out.println(strout);
strout=sysin.readLine();
}
out.println(strout);
}
catch(Exception e)
{
System.out.println("error:"+e);
}
finally
{
in.close();
out.close();
soc.close();
sysin.close();
System.exit(0);
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved