給你一個我寫的示例,用的是基於TCP的Socket技術,你鍛煉一下,改一改,不會改再找我!
客戶端:
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class TcpClient {
public static void main(String[] args) throws Exception
{
//創建客戶端Socket服務,並且制定主機和ank
Socket s = new Socket("192.168.1.104",10002);//連接固定的主機和埠
//為了發送數據,獲取Socket中的輸入輸出流
OutputStream out = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = null;
//讀取伺服器發過來的數據
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
while((line = br.readLine())!=null)
{
out.write(line.getBytes());
if("886".equals(line))
break;
int len = in.read(buf);
String content = new String(buf,0,len);
System.out.println("Server:"+content);
}
s.close();
}
}
伺服器:
/*
* 需求分析:
* 使用TCP協議,寫伺服器端。做到伺服器能收到客戶端的信息,也能向客戶端發送信息
* */
package JavaNetProgramming;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class TcpServer {
public static void main(String[] args) throws Exception
{
//建立伺服器的Socket服務,並且監聽一個埠
ServerSocket ss = new ServerSocket(10002);
Socket s = ss.accept();
InputStream is = s.getInputStream();
//從伺服器端向客戶端發送數據
OutputStream out = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = null;
while(true)
{
//通過accept()方法獲得客戶端傳過來的Socket對象
// System.out.println("getByNanme():"+s.getInetAddress());
System.out.print("getHostAddress():"+s.getInetAddress().getHostAddress());
//獲取客戶端發過來的數據,就要使用客戶端對象的讀取流來讀取數據
byte[] buf = new byte[1024];
int len = is.read(buf);//把流中數據讀到位元組數組中
String content = new String(buf,0,len);
System.out.println(" "+content);
if("886".equals(content))
break;
while((line = br.readLine())!=null)
{
out.write(line.getBytes());
break;
}
}
s.close(); //循環內有判斷語句,這句話才不出錯
ss.close();
}
}