?? java_socket.txt
字號(hào):
server:
import java.net.*;
import java.io.*;
import java.lang.*;
public class myServer{
public static void main(String args[]){
ServerSocket server;
Socket socket;
String s;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;
try{
//在端口注冊(cè)服務(wù)
server=new ServerSocket(9000);
socket=server.accept(); //監(jiān)聽(tīng)窗口,等待連接
System.out.println("server ok");
System.out.println("************************************************");
System.out.println("");
//獲得對(duì)應(yīng)Socket的輸入/輸出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立數(shù)據(jù)流
DIS=new DataInputStream(Is);
PS=new PrintStream(Os);
DataInputStream in=new DataInputStream(System.in);
while(true){
System.out.println("");
System.out.println("please wait client's message...");
System.out.println("");
s=DIS.readLine(); //讀入從client傳來(lái)的字符串
System.out.println("client said:"+s); //打印字符串
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
System.out.print("you say:");
s=in.readLine(); //讀取用戶(hù)輸入的字符串
PS.println(s); //將讀取得字符串傳給client
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
}
//關(guān)閉連接
DIS.close(); //關(guān)閉數(shù)據(jù)輸入流
PS.close(); //關(guān)閉數(shù)據(jù)輸出流
Is.close(); //關(guān)閉輸入流
Os.close(); //關(guān)閉輸出流
socket.close(); //關(guān)閉sockey
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
}
client:
import java.net.*;
import java.io.*;
import java.lang.*;
public class myClient{
public static void main(String args[]){
String host = "";
Socket socket;
String s="";
String len;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
DataOutputStream DOS;
PrintStream PS;
try{
socket=new Socket(host,9000);
System.out.println("client ok");
System.out.println("************************************************");
System.out.println("");
//獲得對(duì)應(yīng)socket的輸入/輸出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立數(shù)據(jù)流
DIS=new DataInputStream(Is);
DOS=new DataOutputStream(Os);
PS=new PrintStream(Os);
DataInputStream in=new DataInputStream(System.in);
while(true){
System.out.print("you say:");
s=in.readLine(); //讀取用戶(hù)輸入的字符串
PS.println(s); //將讀取得字符串傳給server
//DOS.write(s.getBytes());
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
else
{
System.out.println("");
System.out.println("please wait server's message...");
System.out.println("");
}
s=DIS.readLine(); //從服務(wù)器獲得字符串
System.out.println("server said:"+s); //打印字符串
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
}
//關(guān)閉連接
DIS.close(); //關(guān)閉數(shù)據(jù)輸入流
PS.close(); //關(guān)閉數(shù)據(jù)輸出流
Is.close(); //關(guān)閉輸入流
Os.close(); //關(guān)閉輸出流
socket.close(); //關(guān)閉socket
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -