導航:首頁 > 編程語言 > JavaSocket

JavaSocket

發布時間:2022-01-15 12:31:40

java做什麼會用到socket

1、web項目的話一般用到的socket比較少,因為web項目的話一般運用了一些框架,它們幫你把這些東西都封裝了,所以一般不會用到。
2、socket能然你較常接觸主要是在網路編程中,很多東西沒人幫你封裝好,你要自己親手去敲,去了解。比如你自己寫一個聊天系統,你就會較廣泛的去運用到socket

❷ 用Java 的socket實現客戶端的功能

//服務端程序:
importjava.io.*;
importjava.net.*;

publicclassTCPServer{
publicstaticvoidmain(String[]args)throwsIOException{
newTCPServer().init();
}
@SuppressWarnings("static-access")
privatevoidinit()throwsIOException{
@SuppressWarnings("resource")
ServerSocketserver=newServerSocket(1000);
Socketclient=null;
while(true){
try{
client=server.accept();
BufferedInputStreambis=newBufferedInputStream(client.getInputStream());
byte[]b=newbyte[1024];
intlen=0;
Stringmessage="";
while((len=bis.read(b))!=-1){
message=newString(b,0,len);
System.out.print("客戶端:"+client.getInetAddress().getLocalHost().getHostAddress()+"發來消息:"+message);
if("byte".equals(message.trim()))
client.close();
PrintWriterpw=newPrintWriter(client.getOutputStream(),true);
pw.println(message);
}
}catch(Exceptione){
System.err.println("客戶端:"+client.getInetAddress().getLocalHost().getHostAddress()+"已斷開連接!");
}
}
}
}
//客戶端程序:
importjava.io.*;
importjava.net.Socket;

{
publicstaticvoidmain(String[]args)throwsIOException{
newTCPClient().init();
}
privatevoidinit()throwsIOException{
@SuppressWarnings("resource")
finalSocketclient=newSocket("127.0.0.1",1000);
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
Stringsend="";
while(true){
send=in.readLine();
PrintWriterout=newPrintWriter(client.getOutputStream(),true);
if(!"byte".equals(send.trim()))
out.println(send);
else{
out.println(send);
System.exit(0);
}
newThread(newTCPClient(){
@SuppressWarnings("static-access")
publicvoidrun(){
try{
BufferedInputStreambis=newBufferedInputStream(client.getInputStream());
byte[]b=newbyte[1024];
intlen=0;
while((len=bis.read(b))!=-1){
System.out.println("伺服器:"+client.getInetAddress().getLocalHost().getHostAddress()+"發來消息:"+newString(b,0,len).trim());
}
}catch(IOExceptione){
System.err.println("連接伺服器失敗!");
}
}
}).start();
}
}
publicvoidrun(){}
}

//伺服器測試結果:

客戶端:192.168.0.200發來消息:001 byte

客戶端:192.168.0.200發來消息:byte

客戶端:192.168.0.200 已斷開連接!

客戶端:192.168.0.200發來消息:adasd

客戶端:192.168.0.200 已斷開連接!

//客戶端測試結果:

---001號客戶端--

001byte

伺服器:192.168.0.200發來消息:001byte

byte //001禮貌說跟伺服器說byte

---002號客戶端--

adasd //002客戶端直接關閉程序

伺服器:192.168.0.200發來消息:adasd

❸ java中serversocket是什麼意思

serversocket 建立的是socket的服務端,
socket建立的是客戶端。
例子

socket和serversocket (2010-05-07 04:17:11)轉載▼
public class Server {
public static void main(String[] args) {
Socket socket=null;
BufferedReader br=null;
PrintWriter pw=null;
try {
//創建伺服器,並開放3081埠
ServerSocket server=new ServerSocket(3081);
while(true){

//監聽伺服器埠,一旦有數據發送過來,那麼就將數據封裝成socket對象
//如果沒有數據發送過來,那麼這時處於線程阻塞狀態,不會向下繼續執行
socket=server.accept();
System.out.println("客戶端信息:"+socket.getRemoteSocketAddress());
//從socket中得到讀取流,該流中有客戶端發送過來的數據
InputStream in=socket.getInputStream();
//InputStreamReader將位元組流轉化為字元流
br=new BufferedReader(new InputStreamReader(in));
//行讀取客戶端數據
String info=br.readLine();
System.out.println(info);

OutputStream out=socket.getOutputStream();
pw=new PrintWriter(out);
pw.println("伺服器說:我扁死你");
pw.flush();
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

try {
pw.close();
br.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}
public class Client {
public static void main(String[] args) {
Socket socket=null;
PrintWriter pw=null;
BufferedReader br=null;
try {
//創建socket對象,並指明伺服器的IP地址和埠號
socket=new Socket("localhost",3081);
//得到socket發送數據的輸出流
OutputStream out=socket.getOutputStream();
//將位元組流包裝成字元流
pw=new PrintWriter(out);

//向伺服器發送數據
pw.println("客戶端說:建軍悶燒");
//刷新流,確保數據能寫到伺服器
pw.flush();

InputStream in=socket.getInputStream();

br=new BufferedReader(new InputStreamReader(in));
String info=br.readLine();
System.out.println(info);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
pw.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Client {
public static void main(String[] args) {
Socket socket=null;
PrintWriter pw=null;
BufferedReader br=null;
try {
//創建socket對象,並指明伺服器的IP地址和埠號
socket=new Socket("localhost",3081);
//得到socket發送數據的輸出流
OutputStream out=socket.getOutputStream();
//將位元組流包裝成字元流
pw=new PrintWriter(out);

//向伺服器發送數據
pw.println("客戶端說:建軍悶燒");
//刷新流,確保數據能寫到伺服器
pw.flush();

InputStream in=socket.getInputStream();

br=new BufferedReader(new InputStreamReader(in));
String info=br.readLine();
System.out.println(info);

} catch (Exception e) {
// TODO

❹ 用JAVA寫一個SOCKET 接收TCP發來的消息

服務端監聽:ServerSocket server=new ServerSocket(port);//port:綁定的埠號
Socket client=server.accept()();//監聽埠,一旦取得連接則獲得客戶端的socket連接對象client

客戶端: Socket s=new Socket(ip,port);//要連接的伺服器的ip以及埠號

如果正常連接上之後,socket的對象可以獲得InputStream和OutputStreame,然後就可以進行通信了

完成通信之後,執行socket對象的close()方法關閉連接,完成一次完整的socket連接

❺ java socket有什麼作用

所謂socket通常也稱作"套接字",用於描述IP地址和埠,是一個通信鏈的句柄。應用程序通常通過"套接字"向網路發出請求或者應答網路請求。
以J2SDK-1.3為例,Socket和ServerSocket類庫位於java.net包中。ServerSocket用於伺服器端,Socket是建立網路連接時使用的。在連接成功時,應用程序兩端都會產生一個Socket實例,操作這個實例,完成所需的會話。對於一個網路連接來說,套接字是平等的,並沒有差別,不因為在伺服器端或在客戶端而產生不同級別。不管是Socket還是ServerSocket它們的工作都是通過SocketImpl類及其子類完成的。
重要的Socket API:
java.net.Socket繼承於java.lang.Object,有八個構造器,其方法並不多,下面介紹使用最頻繁的三個方法,其它方法大家可以見JDK-1.3文檔。
. Accept方法用於產生"阻塞",直到接受到一個連接,並且返回一個客戶端的Socket對象實例。"阻塞"是一個術語,它使程序運行暫時"停留"在這個地方,直到一個會話產生,然後程序繼續;通常"阻塞"是由循環產生的。
. getInputStream方法獲得網路連接輸入,同時返回一個InputStream對象實例,。
. getOutputStream方法連接的另一端將得到輸入,同時返回一個OutputStream對象實例。
注意:其中getInputStream和getOutputStream方法均會產生一個IOException,它必須被捕獲,因為它們返回的流對象,通常都會被另一個流對象使用。
編輯本段ServerSocket類例子
int PORT = 8888; // 偵聽埠
// 創建ServerSocket
ServerSocket serverSocket = new ServerSocket(PORT);
// 開始循環
while (true) {
// 等待連接
Socket socket = serverSocket.accept();
// 處理鏈接的線程類
ServerThread st = new ServerThread(socket);
// 啟動線程處理
new Thread(st).start();
}
編輯本段客戶端的例子
int PORT = 8888; // 偵聽埠
// 建立連接
socket = new Socket(「127.0.0.1」, 8888);
// 輸入數據的讀取
BufferedReader netIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 寫入數據
PrintWriter netOut = new PrintWriter(socket.getOutputStream());

❻ java Socket通信原理

具體如下:

首先socket 通信是基於TCP/IP 網路層上的一種傳送方式,我們通常把TCP和UDP稱為傳輸層。其中UDP是一種面向無連接的傳輸層協議。UDP不關心對端是否真正收到了傳送過去的數據。

如果需要檢查對端是否收到分組數據包,或者對端是否連接到網路,則需要在應用程序中實現。UDP常用在分組數據較少或多播、廣播通信以及視頻通信等多媒體領域。

在這里我們不進行詳細討論,這里主要講解的是基於TCP/IP協議下的socket通信。

socket是基於應用服務與TCP/IP通信之間的一個抽象,他將TCP/IP協議裡面復雜的通信邏輯進行分裝。

服務端初始化ServerSocket,然後對指定的埠進行綁定,接著對埠及進行監聽,通過調用accept方法阻塞。

此時,如果客戶端有一個socket連接到服務端,那麼服務端通過監聽和accept方法可以與客戶端進行連接。

Java是一門面向對象編程語言,不僅吸收了C++語言的各種優點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強大和簡單易用兩個特徵。

Java語言作為靜態面向對象編程語言的代表,極好地實現了面向對象理論,允許程序員以優雅的思維方式進行復雜的編程。

Java具有簡單性、面向對象、分布式、健壯性、安全性、平台獨立與可移植性、多線程、動態性等特點。Java可以編寫桌面應用程序、Web應用程序、分布式系統和嵌入式系統應用程序等。

❼ JAVA socket通信

publicclassClient{
publicstaticvoidmain(String[]args){
Strings=null;
Socketmysocket;
DataInputStreamin=null;
DataOutputStreamout=null;
try{
mysocket=newSocket("127.0.0.1",4331);
in=newDataInputStream(mysocket.getInputStream());
out=newDataOutputStream(mysocket.getOutputStream());
for(intk=1;k<100;k=k+2){
out.writeUTF(""+k);
s=in.readUTF();
System.out.println("客戶收到"+s);
Thread.sleep(500);
}
}catch(Exceptione){
System.out.println("伺服器已斷開"+e);
}
}
}

publicclassServer{
publicstaticvoidmain(String[]args){
ServerSocketserver=null;
Socketyou=null;
Strings=null;
DataOutputStreamout=null;
DataInputStreamin=null;
try{
server=newServerSocket(4331);
}catch(Exceptione){
System.out.println(e);
}
try{
System.out.println("等待客戶呼叫");
you=server.accept();
out=newDataOutputStream(you.getOutputStream());
in=newDataInputStream(you.getInputStream());
while(true){
s=in.readUTF();
intm=Integer.parseInt(s);
out.writeUTF("你好,我是伺服器");
out.writeUTF("你說的數乘2後是:"+2*m);
System.out.println("伺服器收到:"+s);
Thread.sleep(500);
}
}catch(Exceptione){
System.out.println("客戶端已斷開"+e);
}
}
}

很簡單的伺服器客戶端程序

❽ JAVA Socket

呵呵,我學Java也遇到了很多問題,有時候都不知道怎麼辦才好。學習一門語言不是件容易的事情,要堅持下去!我能說的也就只有這些了,怎麼做還要看你自己!
加油吧!

❾ java中如何創建socket連接的過程

這是我寫過的一個簡單聊天軟體客戶端 你參考下

importjava.util.*;
importjava.io.*;
importjava.net.*;
importjava.awt.*;
importjavax.swing.*;
importjava.awt.event.*;

{
privateJTextAreajta=newJTextArea();
privateJTextFieldjtf=newJTextField();
privateJComboBox<String>jcb=newJComboBox<String>();
privateJButtonjbsend=newJButton("send");
privateJButtonjbrefresh=newJButton("refresh");
privateInputStreaminput;
privateOutputStreamoutput;
private Socketsocket;
publicstaticStringSERVER_IP="192.168.1.101";
publicstaticintSERVER_PORT=8888;
//Message1->refreshmessage
//Message2->sendmessage
publictestChatClient()
{
initComponents();
try
{
socket=newSocket(SERVER_IP,SERVER_PORT);
input=socket.getInputStream();
output=socket.getOutputStream();
}
catch(IOExceptione)
{
System.err.println(e);
}
jbrefresh.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEvente)
{
jta.setText("");
try
{
if(socket==null)
socket=newSocket(SERVER_IP,SERVER_PORT);
output.write(0x31);
}
catch(IOExceptionex)
{
JOptionPane.showConfirmDialog(null,ex);
}
}
});
jbsend.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEvente)
{
if(jtf.getText()==null||jtf.getText().equals(""))
return;
if(jtf.getText().length()>=400)
{
JOptionPane.showConfirmDialog(null,"最大字數不能超過400");
return;
}
try
{
Stringdestination=jcb.getSelectedItem().toString();
Stringmessage=jtf.getText();
if(socket==null)
socket=newSocket(SERVER_IP,SERVER_PORT);
byte[]temp=newbyte[3+destination.getBytes().length+message.getBytes().length];
temp[0]=0x32;
temp[1]=(byte)destination.getBytes().length;
inti=2;
for(intj=0;j<destination.getBytes().length;i++,j++)
temp[i]=destination.getBytes()[j];
temp[i++]=(byte)message.getBytes().length;
for(intj=0;j<message.getBytes().length;i++,j++)
{
temp[i]=message.getBytes()[j];
System.out.println();
}
output.write(temp);
jta.append("me: ");
jta.append(jtf.getText());
jta.append(" ");
jtf.setText("");
}
catch(IOExceptionex)
{
System.err.println(ex);
}
}
});
try
{
jbrefresh.doClick();
while(true)
{
byte[]tempBytes=newbyte[1000];
input.read(tempBytes);
intcommand=tempBytes[0]-0x30;
//intreadLength=input.read();
switch(command)
{
case1:
{
intreadLength=tempBytes[1];
String[]temp=newString(tempBytes,2,readLength,"UTF-8").split(";");
jcb.removeAllItems();
if(temp.length==0&&temp[0].equals(""))
return;
for(inti=0;i<temp.length;i++)
{
jcb.addItem(temp[i]);
}
jcb.setSelectedIndex(0);
break;
}
case2:
{
intreadLength1=tempBytes[1];
jta.append(newString(tempBytes,2,readLength1,"UTF-8")+" ");
intreadLength2=tempBytes[2+readLength1];
jta.append(newString(tempBytes,3+readLength1,readLength2,"UTF-8")+" ");
break;
}
}
}
}
catch(IOExceptione)
{
System.err.println(e);
}
}
publicstaticvoidmain(String[]args){
testChatClientframe=newtestChatClient();
}
publicvoidinitComponents()
{
setLayout(newBorderLayout());
JPaneljpNorth=newJPanel();
jpNorth.setLayout(newBorderLayout());
jpNorth.add(jcb,BorderLayout.CENTER);
jpNorth.add(jbrefresh,BorderLayout.EAST);
JPaneljpSouth=newJPanel();
jpSouth.setLayout(newBorderLayout());
jpSouth.add(jtf,BorderLayout.CENTER);
jpSouth.add(jbsend,BorderLayout.EAST);
add(jpNorth,BorderLayout.NORTH);
add(jpSouth,BorderLayout.SOUTH);
add(newJScrollPane(jta),BorderLayout.CENTER);
this.getRootPane().setDefaultButton(jbsend);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,600);
setVisible(true);
}
}

❿ java中的socket是什麼意思

所謂socket通常也稱作"套接字",用於描述IP地址和埠,是一個通信鏈的句柄。應用程序通常通過"套接字"向網路發出請求或者應答網路請求。
以J2SDK-1.3為例,Socket和ServerSocket類庫位於java.net包中。ServerSocket用於伺服器端,Socket是建立網路連接時使用的。在連接成功時,應用程序兩端都會產生一個Socket實例,操作這個實例,完成所需的會話。對於一個網路連接來說,套接字是平等的,並沒有差別,不因為在伺服器端或在客戶端而產生不同級別。不管是Socket還是ServerSocket它們的工作都是通過SocketImpl類及其子類完成的。
重要的Socket API:
java.net.Socket繼承於java.lang.Object,有八個構造器,其方法並不多,下面介紹使用最頻繁的三個方法,其它方法大家可以見JDK-1.3文檔。
. Accept方法用於產生"阻塞",直到接受到一個連接,並且返回一個客戶端的Socket對象實例。"阻塞"是一個術語,它使程序運行暫時"停留"在這個地方,直到一個會話產生,然後程序繼續;通常"阻塞"是由循環產生的。
. getInputStream方法獲得網路連接輸入,同時返回一個InputStream對象實例。
. getOutputStream方法連接的另一端將得到輸入,同時返回一個OutputStream對象實例。
注意:其中getInputStream和getOutputStream方法均會產生一個IOException,它必須被捕獲,因為它們返回的流對象,通常都會被另一個流對象使用。
2ServerSocket類例子編輯

package com.lanber.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
/**
* 注意:Socket的發送與接收是需要同步進行的,即客戶端發送一條信息,伺服器必需先接收這條信息,
* 而後才可以向客戶端發送信息,否則將會有運行時出錯。
* @param args
*/
public static void main(String[] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(8888);
//伺服器接收到客戶端的數據後,創建與此客戶端對話的Socket
Socket socket = ss.accept();
//用於向客戶端發送數據的輸出流
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//用於接收客戶端發來的數據的輸入流
DataInputStream dis = new DataInputStream(socket.getInputStream());
System.out.println("伺服器接收到客戶端的連接請求:" + dis.readUTF());
//伺服器向客戶端發送連接成功確認信息
dos.writeUTF("接受連接請求,連接成功!");
//不需要繼續使用此連接時,關閉連接
socket.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

3客戶端的例子編輯
package com.lanber.socket;
importjava.io.DataInputStream;
import java.io.DataOutputStream;
importjava.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientDemo {
/**
* @param args
*/
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost",8888);
//獲取輸出流,用於客戶端向伺服器端發送數據
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//獲取輸入流,用於接收伺服器端發送來的數據
DataInputStream dis = new DataInputStream(socket.getInputStream());
//客戶端向伺服器端發送數據
dos.writeUTF("我是客戶端,請求連接!");
//列印出從伺服器端接收到的數據
System.out.println(dis.readUTF());
//不需要繼續使用此連接時,記得關閉哦
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

閱讀全文

與JavaSocket相關的資料

熱點內容
調研編譯寫信息 瀏覽:857
python馮諾依曼 瀏覽:415
同時安裝多個app有什麼影響 瀏覽:251
奧術殺戮命令宏 瀏覽:181
用sdes加密明文字母e 瀏覽:358
單片機原理及應用試題 瀏覽:423
易語言開啟指定文件夾 瀏覽:38
馬思純參加密室大逃脫 瀏覽:319
文件夾冬季澆築溫度 瀏覽:710
京東有返點的aPp叫什麼 瀏覽:601
如何查看u點家庭伺服器是幾兆 瀏覽:262
python應用介面怎麼接 瀏覽:67
腐蝕怎麼進不去伺服器啊 瀏覽:359
linuxcpiogz 瀏覽:630
安卓中的布局是什麼文件 瀏覽:397
dex反編譯部分代碼無法查看 瀏覽:463
linuxandroid編譯 瀏覽:603
程序員電視劇20集 瀏覽:910
怎麼擴建文件夾 瀏覽:160
波普諾社會學pdf 瀏覽:98